3 * https://www.mediawiki.org/wiki/OOjs_UI
5 * Copyright 2011–2017 OOjs UI Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2017-05-31T19:07:36Z
16 * Namespace for all classes, static methods and static properties.
48 * Constants for MouseEvent.which
52 OO
.ui
.MouseButtons
= {
65 * Generate a unique ID for element
69 OO
.ui
.generateElementId = function () {
71 return 'oojsui-' + OO
.ui
.elementId
;
75 * Check if an element is focusable.
76 * Inspired by :focusable in jQueryUI v1.11.4 - 2015-04-14
78 * @param {jQuery} $element Element to test
79 * @return {boolean} Element is focusable
81 OO
.ui
.isFocusableElement = function ( $element
) {
83 element
= $element
[ 0 ];
85 // Anything disabled is not focusable
86 if ( element
.disabled
) {
90 // Check if the element is visible
92 // This is quicker than calling $element.is( ':visible' )
93 $.expr
.pseudos
.visible( element
) &&
94 // Check that all parents are visible
95 !$element
.parents().addBack().filter( function () {
96 return $.css( this, 'visibility' ) === 'hidden';
102 // Check if the element is ContentEditable, which is the string 'true'
103 if ( element
.contentEditable
=== 'true' ) {
107 // Anything with a non-negative numeric tabIndex is focusable.
108 // Use .prop to avoid browser bugs
109 if ( $element
.prop( 'tabIndex' ) >= 0 ) {
113 // Some element types are naturally focusable
114 // (indexOf is much faster than regex in Chrome and about the
115 // same in FF: https://jsperf.com/regex-vs-indexof-array2)
116 nodeName
= element
.nodeName
.toLowerCase();
117 if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName
) !== -1 ) {
121 // Links and areas are focusable if they have an href
122 if ( ( nodeName
=== 'a' || nodeName
=== 'area' ) && $element
.attr( 'href' ) !== undefined ) {
130 * Find a focusable child
132 * @param {jQuery} $container Container to search in
133 * @param {boolean} [backwards] Search backwards
134 * @return {jQuery} Focusable child, or an empty jQuery object if none found
136 OO
.ui
.findFocusable = function ( $container
, backwards
) {
137 var $focusable
= $( [] ),
138 // $focusableCandidates is a superset of things that
139 // could get matched by isFocusableElement
140 $focusableCandidates
= $container
141 .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' );
144 $focusableCandidates
= Array
.prototype.reverse
.call( $focusableCandidates
);
147 $focusableCandidates
.each( function () {
148 var $this = $( this );
149 if ( OO
.ui
.isFocusableElement( $this ) ) {
158 * Get the user's language and any fallback languages.
160 * These language codes are used to localize user interface elements in the user's language.
162 * In environments that provide a localization system, this function should be overridden to
163 * return the user's language(s). The default implementation returns English (en) only.
165 * @return {string[]} Language codes, in descending order of priority
167 OO
.ui
.getUserLanguages = function () {
172 * Get a value in an object keyed by language code.
174 * @param {Object.<string,Mixed>} obj Object keyed by language code
175 * @param {string|null} [lang] Language code, if omitted or null defaults to any user language
176 * @param {string} [fallback] Fallback code, used if no matching language can be found
177 * @return {Mixed} Local value
179 OO
.ui
.getLocalValue = function ( obj
, lang
, fallback
) {
182 // Requested language
186 // Known user language
187 langs
= OO
.ui
.getUserLanguages();
188 for ( i
= 0, len
= langs
.length
; i
< len
; i
++ ) {
195 if ( obj
[ fallback
] ) {
196 return obj
[ fallback
];
198 // First existing language
199 for ( lang
in obj
) {
207 * Check if a node is contained within another node
209 * Similar to jQuery#contains except a list of containers can be supplied
210 * and a boolean argument allows you to include the container in the match list
212 * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in
213 * @param {HTMLElement} contained Node to find
214 * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants
215 * @return {boolean} The node is in the list of target nodes
217 OO
.ui
.contains = function ( containers
, contained
, matchContainers
) {
219 if ( !Array
.isArray( containers
) ) {
220 containers
= [ containers
];
222 for ( i
= containers
.length
- 1; i
>= 0; i
-- ) {
223 if ( ( matchContainers
&& contained
=== containers
[ i
] ) || $.contains( containers
[ i
], contained
) ) {
231 * Return a function, that, as long as it continues to be invoked, will not
232 * be triggered. The function will be called after it stops being called for
233 * N milliseconds. If `immediate` is passed, trigger the function on the
234 * leading edge, instead of the trailing.
236 * Ported from: http://underscorejs.org/underscore.js
238 * @param {Function} func Function to debounce
239 * @param {number} [wait=0] Wait period in milliseconds
240 * @param {boolean} [immediate] Trigger on leading edge
241 * @return {Function} Debounced function
243 OO
.ui
.debounce = function ( func
, wait
, immediate
) {
248 later = function () {
251 func
.apply( context
, args
);
254 if ( immediate
&& !timeout
) {
255 func
.apply( context
, args
);
257 if ( !timeout
|| wait
) {
258 clearTimeout( timeout
);
259 timeout
= setTimeout( later
, wait
);
265 * Puts a console warning with provided message.
267 * @param {string} message Message
269 OO
.ui
.warnDeprecation = function ( message
) {
270 if ( OO
.getProp( window
, 'console', 'warn' ) !== undefined ) {
271 // eslint-disable-next-line no-console
272 console
.warn( message
);
277 * Returns a function, that, when invoked, will only be triggered at most once
278 * during a given window of time. If called again during that window, it will
279 * wait until the window ends and then trigger itself again.
281 * As it's not knowable to the caller whether the function will actually run
282 * when the wrapper is called, return values from the function are entirely
285 * @param {Function} func Function to throttle
286 * @param {number} wait Throttle window length, in milliseconds
287 * @return {Function} Throttled function
289 OO
.ui
.throttle = function ( func
, wait
) {
290 var context
, args
, timeout
,
294 previous
= OO
.ui
.now();
295 func
.apply( context
, args
);
298 // Check how long it's been since the last time the function was
299 // called, and whether it's more or less than the requested throttle
300 // period. If it's less, run the function immediately. If it's more,
301 // set a timeout for the remaining time -- but don't replace an
302 // existing timeout, since that'd indefinitely prolong the wait.
303 var remaining
= wait
- ( OO
.ui
.now() - previous
);
306 if ( remaining
<= 0 ) {
307 // Note: unless wait was ridiculously large, this means we'll
308 // automatically run the first time the function was called in a
309 // given period. (If you provide a wait period larger than the
310 // current Unix timestamp, you *deserve* unexpected behavior.)
311 clearTimeout( timeout
);
313 } else if ( !timeout
) {
314 timeout
= setTimeout( run
, remaining
);
320 * A (possibly faster) way to get the current timestamp as an integer
322 * @return {number} Current timestamp, in milliseconds since the Unix epoch
324 OO
.ui
.now
= Date
.now
|| function () {
325 return new Date().getTime();
329 * Reconstitute a JavaScript object corresponding to a widget created by
330 * the PHP implementation.
332 * This is an alias for `OO.ui.Element.static.infuse()`.
334 * @param {string|HTMLElement|jQuery} idOrNode
335 * A DOM id (if a string) or node for the widget to infuse.
336 * @return {OO.ui.Element}
337 * The `OO.ui.Element` corresponding to this (infusable) document node.
339 OO
.ui
.infuse = function ( idOrNode
) {
340 return OO
.ui
.Element
.static.infuse( idOrNode
);
345 * Message store for the default implementation of OO.ui.msg
347 * Environments that provide a localization system should not use this, but should override
348 * OO.ui.msg altogether.
353 // Tool tip for a button that moves items in a list down one place
354 'ooui-outline-control-move-down': 'Move item down',
355 // Tool tip for a button that moves items in a list up one place
356 'ooui-outline-control-move-up': 'Move item up',
357 // Tool tip for a button that removes items from a list
358 'ooui-outline-control-remove': 'Remove item',
359 // Label for the toolbar group that contains a list of all other available tools
360 'ooui-toolbar-more': 'More',
361 // Label for the fake tool that expands the full list of tools in a toolbar group
362 'ooui-toolgroup-expand': 'More',
363 // Label for the fake tool that collapses the full list of tools in a toolbar group
364 'ooui-toolgroup-collapse': 'Fewer',
365 // Default label for the accept button of a confirmation dialog
366 'ooui-dialog-message-accept': 'OK',
367 // Default label for the reject button of a confirmation dialog
368 'ooui-dialog-message-reject': 'Cancel',
369 // Title for process dialog error description
370 'ooui-dialog-process-error': 'Something went wrong',
371 // Label for process dialog dismiss error button, visible when describing errors
372 'ooui-dialog-process-dismiss': 'Dismiss',
373 // Label for process dialog retry action button, visible when describing only recoverable errors
374 'ooui-dialog-process-retry': 'Try again',
375 // Label for process dialog retry action button, visible when describing only warnings
376 'ooui-dialog-process-continue': 'Continue',
377 // Label for the file selection widget's select file button
378 'ooui-selectfile-button-select': 'Select a file',
379 // Label for the file selection widget if file selection is not supported
380 'ooui-selectfile-not-supported': 'File selection is not supported',
381 // Label for the file selection widget when no file is currently selected
382 'ooui-selectfile-placeholder': 'No file is selected',
383 // Label for the file selection widget's drop target
384 'ooui-selectfile-dragdrop-placeholder': 'Drop file here'
388 * Get a localized message.
390 * After the message key, message parameters may optionally be passed. In the default implementation,
391 * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc.
392 * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as
393 * they support unnamed, ordered message parameters.
395 * In environments that provide a localization system, this function should be overridden to
396 * return the message translated in the user's language. The default implementation always returns
397 * English messages. An example of doing this with [jQuery.i18n](https://github.com/wikimedia/jquery.i18n)
401 * var i, iLen, button,
402 * messagePath = 'oojs-ui/dist/i18n/',
403 * languages = [ $.i18n().locale, 'ur', 'en' ],
406 * for ( i = 0, iLen = languages.length; i < iLen; i++ ) {
407 * languageMap[ languages[ i ] ] = messagePath + languages[ i ].toLowerCase() + '.json';
410 * $.i18n().load( languageMap ).done( function() {
411 * // Replace the built-in `msg` only once we've loaded the internationalization.
412 * // OOjs UI uses `OO.ui.deferMsg` for all initially-loaded messages. So long as
413 * // you put off creating any widgets until this promise is complete, no English
414 * // will be displayed.
415 * OO.ui.msg = $.i18n;
417 * // A button displaying "OK" in the default locale
418 * button = new OO.ui.ButtonWidget( {
419 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
422 * $( 'body' ).append( button.$element );
424 * // A button displaying "OK" in Urdu
425 * $.i18n().locale = 'ur';
426 * button = new OO.ui.ButtonWidget( {
427 * label: OO.ui.msg( 'ooui-dialog-message-accept' ),
430 * $( 'body' ).append( button.$element );
433 * @param {string} key Message key
434 * @param {...Mixed} [params] Message parameters
435 * @return {string} Translated message with parameters substituted
437 OO
.ui
.msg = function ( key
) {
438 var message
= messages
[ key
],
439 params
= Array
.prototype.slice
.call( arguments
, 1 );
440 if ( typeof message
=== 'string' ) {
441 // Perform $1 substitution
442 message
= message
.replace( /\$(\d+)/g, function ( unused
, n
) {
443 var i
= parseInt( n
, 10 );
444 return params
[ i
- 1 ] !== undefined ? params
[ i
- 1 ] : '$' + n
;
447 // Return placeholder if message not found
448 message
= '[' + key
+ ']';
455 * Package a message and arguments for deferred resolution.
457 * Use this when you are statically specifying a message and the message may not yet be present.
459 * @param {string} key Message key
460 * @param {...Mixed} [params] Message parameters
461 * @return {Function} Function that returns the resolved message when executed
463 OO
.ui
.deferMsg = function () {
464 var args
= arguments
;
466 return OO
.ui
.msg
.apply( OO
.ui
, args
);
473 * If the message is a function it will be executed, otherwise it will pass through directly.
475 * @param {Function|string} msg Deferred message, or message text
476 * @return {string} Resolved message
478 OO
.ui
.resolveMsg = function ( msg
) {
479 if ( $.isFunction( msg
) ) {
486 * @param {string} url
489 OO
.ui
.isSafeUrl = function ( url
) {
490 // Keep this function in sync with php/Tag.php
491 var i
, protocolWhitelist
;
493 function stringStartsWith( haystack
, needle
) {
494 return haystack
.substr( 0, needle
.length
) === needle
;
497 protocolWhitelist
= [
498 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs',
499 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh',
500 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp'
507 for ( i
= 0; i
< protocolWhitelist
.length
; i
++ ) {
508 if ( stringStartsWith( url
, protocolWhitelist
[ i
] + ':' ) ) {
513 // This matches '//' too
514 if ( stringStartsWith( url
, '/' ) || stringStartsWith( url
, './' ) ) {
517 if ( stringStartsWith( url
, '?' ) || stringStartsWith( url
, '#' ) ) {
525 * Check if the user has a 'mobile' device.
527 * For our purposes this means the user is primarily using an
528 * on-screen keyboard, touch input instead of a mouse and may
529 * have a physically small display.
531 * It is left up to implementors to decide how to compute this
532 * so the default implementation always returns false.
534 * @return {boolean} Use is on a mobile device
536 OO
.ui
.isMobile = function () {
545 * Namespace for OOjs UI mixins.
547 * Mixins are named according to the type of object they are intended to
548 * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be
549 * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget
550 * is intended to be mixed in to an instance of OO.ui.Widget.
558 * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything
559 * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events
560 * connected to them and can't be interacted with.
566 * @param {Object} [config] Configuration options
567 * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added
568 * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2]
570 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample
571 * @cfg {string} [id] The HTML id attribute used in the rendered tag.
572 * @cfg {string} [text] Text to insert
573 * @cfg {Array} [content] An array of content elements to append (after #text).
574 * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML.
575 * Instances of OO.ui.Element will have their $element appended.
576 * @cfg {jQuery} [$content] Content elements to append (after #text).
577 * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName.
578 * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object).
579 * Data can also be specified with the #setData method.
581 OO
.ui
.Element
= function OoUiElement( config
) {
582 this.initialConfig
= config
;
583 // Configuration initialization
584 config
= config
|| {};
588 this.elementId
= null;
590 this.data
= config
.data
;
591 this.$element
= config
.$element
||
592 $( document
.createElement( this.getTagName() ) );
593 this.elementGroup
= null;
596 if ( Array
.isArray( config
.classes
) ) {
597 this.$element
.addClass( config
.classes
.join( ' ' ) );
600 this.setElementId( config
.id
);
603 this.$element
.text( config
.text
);
605 if ( config
.content
) {
606 // The `content` property treats plain strings as text; use an
607 // HtmlSnippet to append HTML content. `OO.ui.Element`s get their
608 // appropriate $element appended.
609 this.$element
.append( config
.content
.map( function ( v
) {
610 if ( typeof v
=== 'string' ) {
611 // Escape string so it is properly represented in HTML.
612 return document
.createTextNode( v
);
613 } else if ( v
instanceof OO
.ui
.HtmlSnippet
) {
616 } else if ( v
instanceof OO
.ui
.Element
) {
622 if ( config
.$content
) {
623 // The `$content` property treats plain strings as HTML.
624 this.$element
.append( config
.$content
);
630 OO
.initClass( OO
.ui
.Element
);
632 /* Static Properties */
635 * The name of the HTML tag used by the element.
637 * The static value may be ignored if the #getTagName method is overridden.
643 OO
.ui
.Element
.static.tagName
= 'div';
648 * Reconstitute a JavaScript object corresponding to a widget created
649 * by the PHP implementation.
651 * @param {string|HTMLElement|jQuery} idOrNode
652 * A DOM id (if a string) or node for the widget to infuse.
653 * @return {OO.ui.Element}
654 * The `OO.ui.Element` corresponding to this (infusable) document node.
655 * For `Tag` objects emitted on the HTML side (used occasionally for content)
656 * the value returned is a newly-created Element wrapping around the existing
659 OO
.ui
.Element
.static.infuse = function ( idOrNode
) {
660 var obj
= OO
.ui
.Element
.static.unsafeInfuse( idOrNode
, false );
661 // Verify that the type matches up.
662 // FIXME: uncomment after T89721 is fixed (see T90929)
664 if ( !( obj instanceof this['class'] ) ) {
665 throw new Error( 'Infusion type mismatch!' );
672 * Implementation helper for `infuse`; skips the type check and has an
673 * extra property so that only the top-level invocation touches the DOM.
676 * @param {string|HTMLElement|jQuery} idOrNode
677 * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved
678 * when the top-level widget of this infusion is inserted into DOM,
679 * replacing the original node; or false for top-level invocation.
680 * @return {OO.ui.Element}
682 OO
.ui
.Element
.static.unsafeInfuse = function ( idOrNode
, domPromise
) {
683 // look for a cached result of a previous infusion.
684 var id
, $elem
, data
, cls
, parts
, parent
, obj
, top
, state
, infusedChildren
;
685 if ( typeof idOrNode
=== 'string' ) {
687 $elem
= $( document
.getElementById( id
) );
689 $elem
= $( idOrNode
);
690 id
= $elem
.attr( 'id' );
692 if ( !$elem
.length
) {
693 throw new Error( 'Widget not found: ' + id
);
695 if ( $elem
[ 0 ].oouiInfused
) {
696 $elem
= $elem
[ 0 ].oouiInfused
;
698 data
= $elem
.data( 'ooui-infused' );
701 if ( data
=== true ) {
702 throw new Error( 'Circular dependency! ' + id
);
705 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
706 state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
707 // restore dynamic state after the new element is re-inserted into DOM under infused parent
708 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
709 infusedChildren
= $elem
.data( 'ooui-infused-children' );
710 if ( infusedChildren
&& infusedChildren
.length
) {
711 infusedChildren
.forEach( function ( data
) {
712 var state
= data
.constructor.static.gatherPreInfuseState( $elem
, data
);
713 domPromise
.done( data
.restorePreInfuseState
.bind( data
, state
) );
719 data
= $elem
.attr( 'data-ooui' );
721 throw new Error( 'No infusion data found: ' + id
);
724 data
= JSON
.parse( data
);
728 if ( !( data
&& data
._
) ) {
729 throw new Error( 'No valid infusion data found: ' + id
);
731 if ( data
._
=== 'Tag' ) {
732 // Special case: this is a raw Tag; wrap existing node, don't rebuild.
733 return new OO
.ui
.Element( { $element
: $elem
} );
735 parts
= data
._
.split( '.' );
736 cls
= OO
.getProp
.apply( OO
, [ window
].concat( parts
) );
737 if ( cls
=== undefined ) {
738 // The PHP output might be old and not including the "OO.ui" prefix
739 // TODO: Remove this back-compat after next major release
740 cls
= OO
.getProp
.apply( OO
, [ OO
.ui
].concat( parts
) );
741 if ( cls
=== undefined ) {
742 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
746 // Verify that we're creating an OO.ui.Element instance
749 while ( parent
!== undefined ) {
750 if ( parent
=== OO
.ui
.Element
) {
755 parent
= parent
.parent
;
758 if ( parent
!== OO
.ui
.Element
) {
759 throw new Error( 'Unknown widget type: id: ' + id
+ ', class: ' + data
._
);
762 if ( domPromise
=== false ) {
764 domPromise
= top
.promise();
766 $elem
.data( 'ooui-infused', true ); // prevent loops
767 data
.id
= id
; // implicit
768 infusedChildren
= [];
769 data
= OO
.copy( data
, null, function deserialize( value
) {
771 if ( OO
.isPlainObject( value
) ) {
773 infused
= OO
.ui
.Element
.static.unsafeInfuse( value
.tag
, domPromise
);
774 infusedChildren
.push( infused
);
775 // Flatten the structure
776 infusedChildren
.push
.apply( infusedChildren
, infused
.$element
.data( 'ooui-infused-children' ) || [] );
777 infused
.$element
.removeData( 'ooui-infused-children' );
780 if ( value
.html
!== undefined ) {
781 return new OO
.ui
.HtmlSnippet( value
.html
);
785 // allow widgets to reuse parts of the DOM
786 data
= cls
.static.reusePreInfuseDOM( $elem
[ 0 ], data
);
787 // pick up dynamic state, like focus, value of form inputs, scroll position, etc.
788 state
= cls
.static.gatherPreInfuseState( $elem
[ 0 ], data
);
790 // eslint-disable-next-line new-cap
791 obj
= new cls( data
);
792 // now replace old DOM with this new DOM.
794 // An efficient constructor might be able to reuse the entire DOM tree of the original element,
795 // so only mutate the DOM if we need to.
796 if ( $elem
[ 0 ] !== obj
.$element
[ 0 ] ) {
797 $elem
.replaceWith( obj
.$element
);
798 // This element is now gone from the DOM, but if anyone is holding a reference to it,
799 // let's allow them to OO.ui.infuse() it and do what they expect (T105828).
800 // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design.
801 $elem
[ 0 ].oouiInfused
= obj
.$element
;
805 obj
.$element
.data( 'ooui-infused', obj
);
806 obj
.$element
.data( 'ooui-infused-children', infusedChildren
);
807 // set the 'data-ooui' attribute so we can identify infused widgets
808 obj
.$element
.attr( 'data-ooui', '' );
809 // restore dynamic state after the new element is inserted into DOM
810 domPromise
.done( obj
.restorePreInfuseState
.bind( obj
, state
) );
815 * Pick out parts of `node`'s DOM to be reused when infusing a widget.
817 * This method **must not** make any changes to the DOM, only find interesting pieces and add them
818 * to `config` (which should then be returned). Actual DOM juggling should then be done by the
819 * constructor, which will be given the enhanced config.
822 * @param {HTMLElement} node
823 * @param {Object} config
826 OO
.ui
.Element
.static.reusePreInfuseDOM = function ( node
, config
) {
831 * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of an HTML DOM node
832 * (and its children) that represent an Element of the same class and the given configuration,
833 * generated by the PHP implementation.
835 * This method is called just before `node` is detached from the DOM. The return value of this
836 * function will be passed to #restorePreInfuseState after the newly created widget's #$element
837 * is inserted into DOM to replace `node`.
840 * @param {HTMLElement} node
841 * @param {Object} config
844 OO
.ui
.Element
.static.gatherPreInfuseState = function () {
849 * Get a jQuery function within a specific document.
852 * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to
853 * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is
855 * @return {Function} Bound jQuery function
857 OO
.ui
.Element
.static.getJQuery = function ( context
, $iframe
) {
858 function wrapper( selector
) {
859 return $( selector
, wrapper
.context
);
862 wrapper
.context
= this.getDocument( context
);
865 wrapper
.$iframe
= $iframe
;
872 * Get the document of an element.
875 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for
876 * @return {HTMLDocument|null} Document object
878 OO
.ui
.Element
.static.getDocument = function ( obj
) {
879 // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable
880 return ( obj
[ 0 ] && obj
[ 0 ].ownerDocument
) ||
881 // Empty jQuery selections might have a context
888 ( obj
.nodeType
=== Node
.DOCUMENT_NODE
&& obj
) ||
893 * Get the window of an element or document.
896 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for
897 * @return {Window} Window object
899 OO
.ui
.Element
.static.getWindow = function ( obj
) {
900 var doc
= this.getDocument( obj
);
901 return doc
.defaultView
;
905 * Get the direction of an element or document.
908 * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for
909 * @return {string} Text direction, either 'ltr' or 'rtl'
911 OO
.ui
.Element
.static.getDir = function ( obj
) {
914 if ( obj
instanceof jQuery
) {
917 isDoc
= obj
.nodeType
=== Node
.DOCUMENT_NODE
;
918 isWin
= obj
.document
!== undefined;
919 if ( isDoc
|| isWin
) {
925 return $( obj
).css( 'direction' );
929 * Get the offset between two frames.
931 * TODO: Make this function not use recursion.
934 * @param {Window} from Window of the child frame
935 * @param {Window} [to=window] Window of the parent frame
936 * @param {Object} [offset] Offset to start with, used internally
937 * @return {Object} Offset object, containing left and top properties
939 OO
.ui
.Element
.static.getFrameOffset = function ( from, to
, offset
) {
940 var i
, len
, frames
, frame
, rect
;
946 offset
= { top
: 0, left
: 0 };
948 if ( from.parent
=== from ) {
952 // Get iframe element
953 frames
= from.parent
.document
.getElementsByTagName( 'iframe' );
954 for ( i
= 0, len
= frames
.length
; i
< len
; i
++ ) {
955 if ( frames
[ i
].contentWindow
=== from ) {
961 // Recursively accumulate offset values
963 rect
= frame
.getBoundingClientRect();
964 offset
.left
+= rect
.left
;
965 offset
.top
+= rect
.top
;
967 this.getFrameOffset( from.parent
, offset
);
974 * Get the offset between two elements.
976 * The two elements may be in a different frame, but in that case the frame $element is in must
977 * be contained in the frame $anchor is in.
980 * @param {jQuery} $element Element whose position to get
981 * @param {jQuery} $anchor Element to get $element's position relative to
982 * @return {Object} Translated position coordinates, containing top and left properties
984 OO
.ui
.Element
.static.getRelativePosition = function ( $element
, $anchor
) {
985 var iframe
, iframePos
,
986 pos
= $element
.offset(),
987 anchorPos
= $anchor
.offset(),
988 elementDocument
= this.getDocument( $element
),
989 anchorDocument
= this.getDocument( $anchor
);
991 // If $element isn't in the same document as $anchor, traverse up
992 while ( elementDocument
!== anchorDocument
) {
993 iframe
= elementDocument
.defaultView
.frameElement
;
995 throw new Error( '$element frame is not contained in $anchor frame' );
997 iframePos
= $( iframe
).offset();
998 pos
.left
+= iframePos
.left
;
999 pos
.top
+= iframePos
.top
;
1000 elementDocument
= iframe
.ownerDocument
;
1002 pos
.left
-= anchorPos
.left
;
1003 pos
.top
-= anchorPos
.top
;
1008 * Get element border sizes.
1011 * @param {HTMLElement} el Element to measure
1012 * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties
1014 OO
.ui
.Element
.static.getBorders = function ( el
) {
1015 var doc
= el
.ownerDocument
,
1016 win
= doc
.defaultView
,
1017 style
= win
.getComputedStyle( el
, null ),
1019 top
= parseFloat( style
? style
.borderTopWidth
: $el
.css( 'borderTopWidth' ) ) || 0,
1020 left
= parseFloat( style
? style
.borderLeftWidth
: $el
.css( 'borderLeftWidth' ) ) || 0,
1021 bottom
= parseFloat( style
? style
.borderBottomWidth
: $el
.css( 'borderBottomWidth' ) ) || 0,
1022 right
= parseFloat( style
? style
.borderRightWidth
: $el
.css( 'borderRightWidth' ) ) || 0;
1033 * Get dimensions of an element or window.
1036 * @param {HTMLElement|Window} el Element to measure
1037 * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties
1039 OO
.ui
.Element
.static.getDimensions = function ( el
) {
1041 doc
= el
.ownerDocument
|| el
.document
,
1042 win
= doc
.defaultView
;
1044 if ( win
=== el
|| el
=== doc
.documentElement
) {
1047 borders
: { top
: 0, left
: 0, bottom
: 0, right
: 0 },
1049 top
: $win
.scrollTop(),
1050 left
: $win
.scrollLeft()
1052 scrollbar
: { right
: 0, bottom
: 0 },
1056 bottom
: $win
.innerHeight(),
1057 right
: $win
.innerWidth()
1063 borders
: this.getBorders( el
),
1065 top
: $el
.scrollTop(),
1066 left
: $el
.scrollLeft()
1069 right
: $el
.innerWidth() - el
.clientWidth
,
1070 bottom
: $el
.innerHeight() - el
.clientHeight
1072 rect
: el
.getBoundingClientRect()
1078 * Get the number of pixels that an element's content is scrolled to the left.
1080 * Adapted from <https://github.com/othree/jquery.rtl-scroll-type>.
1081 * Original code copyright 2012 Wei-Ko Kao, licensed under the MIT License.
1083 * This function smooths out browser inconsistencies (nicely described in the README at
1084 * <https://github.com/othree/jquery.rtl-scroll-type>) and produces a result consistent
1085 * with Firefox's 'scrollLeft', which seems the sanest.
1089 * @param {HTMLElement|Window} el Element to measure
1090 * @return {number} Scroll position from the left.
1091 * If the element's direction is LTR, this is a positive number between `0` (initial scroll position)
1092 * and `el.scrollWidth - el.clientWidth` (furthest possible scroll position).
1093 * If the element's direction is RTL, this is a negative number between `0` (initial scroll position)
1094 * and `-el.scrollWidth + el.clientWidth` (furthest possible scroll position).
1096 OO
.ui
.Element
.static.getScrollLeft
= ( function () {
1097 var rtlScrollType
= null;
1100 var $definer
= $( '<div dir="rtl" style="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll">A</div>' ),
1101 definer
= $definer
[ 0 ];
1103 $definer
.appendTo( 'body' );
1104 if ( definer
.scrollLeft
> 0 ) {
1106 rtlScrollType
= 'default';
1108 definer
.scrollLeft
= 1;
1109 if ( definer
.scrollLeft
=== 0 ) {
1110 // Firefox, old Opera
1111 rtlScrollType
= 'negative';
1113 // Internet Explorer, Edge
1114 rtlScrollType
= 'reverse';
1120 return function getScrollLeft( el
) {
1121 var isRoot
= el
.window
=== el
||
1122 el
=== el
.ownerDocument
.body
||
1123 el
=== el
.ownerDocument
.documentElement
,
1124 scrollLeft
= isRoot
? $( window
).scrollLeft() : el
.scrollLeft
,
1125 // All browsers use the correct scroll type ('negative') on the root, so don't
1126 // do any fixups when looking at the root element
1127 direction
= isRoot
? 'ltr' : $( el
).css( 'direction' );
1129 if ( direction
=== 'rtl' ) {
1130 if ( rtlScrollType
=== null ) {
1133 if ( rtlScrollType
=== 'reverse' ) {
1134 scrollLeft
= -scrollLeft
;
1135 } else if ( rtlScrollType
=== 'default' ) {
1136 scrollLeft
= scrollLeft
- el
.scrollWidth
+ el
.clientWidth
;
1145 * Get the root scrollable element of given element's document.
1147 * On Blink-based browsers (Chrome etc.), `document.documentElement` can't be used to get or set
1148 * the scrollTop property; instead we have to use `document.body`. Changing and testing the value
1149 * lets us use 'body' or 'documentElement' based on what is working.
1151 * https://code.google.com/p/chromium/issues/detail?id=303131
1154 * @param {HTMLElement} el Element to find root scrollable parent for
1155 * @return {HTMLElement} Scrollable parent, `document.body` or `document.documentElement`
1156 * depending on browser
1158 OO
.ui
.Element
.static.getRootScrollableElement = function ( el
) {
1159 var scrollTop
, body
;
1161 if ( OO
.ui
.scrollableElement
=== undefined ) {
1162 body
= el
.ownerDocument
.body
;
1163 scrollTop
= body
.scrollTop
;
1166 if ( body
.scrollTop
=== 1 ) {
1167 body
.scrollTop
= scrollTop
;
1168 OO
.ui
.scrollableElement
= 'body';
1170 OO
.ui
.scrollableElement
= 'documentElement';
1174 return el
.ownerDocument
[ OO
.ui
.scrollableElement
];
1178 * Get closest scrollable container.
1180 * Traverses up until either a scrollable element or the root is reached, in which case the root
1181 * scrollable element will be returned (see #getRootScrollableElement).
1184 * @param {HTMLElement} el Element to find scrollable container for
1185 * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either
1186 * @return {HTMLElement} Closest scrollable container
1188 OO
.ui
.Element
.static.getClosestScrollableContainer = function ( el
, dimension
) {
1190 // Browsers do not correctly return the computed value of 'overflow' when 'overflow-x' and
1191 // 'overflow-y' have different values, so we need to check the separate properties.
1192 props
= [ 'overflow-x', 'overflow-y' ],
1193 $parent
= $( el
).parent();
1195 if ( dimension
=== 'x' || dimension
=== 'y' ) {
1196 props
= [ 'overflow-' + dimension
];
1199 // Special case for the document root (which doesn't really have any scrollable container, since
1200 // it is the ultimate scrollable container, but this is probably saner than null or exception)
1201 if ( $( el
).is( 'html, body' ) ) {
1202 return this.getRootScrollableElement( el
);
1205 while ( $parent
.length
) {
1206 if ( $parent
[ 0 ] === this.getRootScrollableElement( el
) ) {
1207 return $parent
[ 0 ];
1211 val
= $parent
.css( props
[ i
] );
1212 // We assume that elements with 'overflow' (in any direction) set to 'hidden' will never be
1213 // scrolled in that direction, but they can actually be scrolled programatically. The user can
1214 // unintentionally perform a scroll in such case even if the application doesn't scroll
1215 // programatically, e.g. when jumping to an anchor, or when using built-in find functionality.
1216 // This could cause funny issues...
1217 if ( val
=== 'auto' || val
=== 'scroll' ) {
1218 return $parent
[ 0 ];
1221 $parent
= $parent
.parent();
1223 // The element is unattached... return something mostly sane
1224 return this.getRootScrollableElement( el
);
1228 * Scroll element into view.
1231 * @param {HTMLElement} el Element to scroll into view
1232 * @param {Object} [config] Configuration options
1233 * @param {string} [config.duration='fast'] jQuery animation duration value
1234 * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit
1235 * to scroll in both directions
1236 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1238 OO
.ui
.Element
.static.scrollIntoView = function ( el
, config
) {
1239 var position
, animations
, container
, $container
, elementDimensions
, containerDimensions
, $window
,
1240 deferred
= $.Deferred();
1242 // Configuration initialization
1243 config
= config
|| {};
1246 container
= this.getClosestScrollableContainer( el
, config
.direction
);
1247 $container
= $( container
);
1248 elementDimensions
= this.getDimensions( el
);
1249 containerDimensions
= this.getDimensions( container
);
1250 $window
= $( this.getWindow( el
) );
1252 // Compute the element's position relative to the container
1253 if ( $container
.is( 'html, body' ) ) {
1254 // If the scrollable container is the root, this is easy
1256 top
: elementDimensions
.rect
.top
,
1257 bottom
: $window
.innerHeight() - elementDimensions
.rect
.bottom
,
1258 left
: elementDimensions
.rect
.left
,
1259 right
: $window
.innerWidth() - elementDimensions
.rect
.right
1262 // Otherwise, we have to subtract el's coordinates from container's coordinates
1264 top
: elementDimensions
.rect
.top
- ( containerDimensions
.rect
.top
+ containerDimensions
.borders
.top
),
1265 bottom
: containerDimensions
.rect
.bottom
- containerDimensions
.borders
.bottom
- containerDimensions
.scrollbar
.bottom
- elementDimensions
.rect
.bottom
,
1266 left
: elementDimensions
.rect
.left
- ( containerDimensions
.rect
.left
+ containerDimensions
.borders
.left
),
1267 right
: containerDimensions
.rect
.right
- containerDimensions
.borders
.right
- containerDimensions
.scrollbar
.right
- elementDimensions
.rect
.right
1271 if ( !config
.direction
|| config
.direction
=== 'y' ) {
1272 if ( position
.top
< 0 ) {
1273 animations
.scrollTop
= containerDimensions
.scroll
.top
+ position
.top
;
1274 } else if ( position
.top
> 0 && position
.bottom
< 0 ) {
1275 animations
.scrollTop
= containerDimensions
.scroll
.top
+ Math
.min( position
.top
, -position
.bottom
);
1278 if ( !config
.direction
|| config
.direction
=== 'x' ) {
1279 if ( position
.left
< 0 ) {
1280 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ position
.left
;
1281 } else if ( position
.left
> 0 && position
.right
< 0 ) {
1282 animations
.scrollLeft
= containerDimensions
.scroll
.left
+ Math
.min( position
.left
, -position
.right
);
1285 if ( !$.isEmptyObject( animations
) ) {
1286 $container
.stop( true ).animate( animations
, config
.duration
=== undefined ? 'fast' : config
.duration
);
1287 $container
.queue( function ( next
) {
1294 return deferred
.promise();
1298 * Force the browser to reconsider whether it really needs to render scrollbars inside the element
1299 * and reserve space for them, because it probably doesn't.
1301 * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also
1302 * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need
1303 * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow,
1304 * and then reattach (or show) them back.
1307 * @param {HTMLElement} el Element to reconsider the scrollbars on
1309 OO
.ui
.Element
.static.reconsiderScrollbars = function ( el
) {
1310 var i
, len
, scrollLeft
, scrollTop
, nodes
= [];
1311 // Save scroll position
1312 scrollLeft
= el
.scrollLeft
;
1313 scrollTop
= el
.scrollTop
;
1314 // Detach all children
1315 while ( el
.firstChild
) {
1316 nodes
.push( el
.firstChild
);
1317 el
.removeChild( el
.firstChild
);
1320 void el
.offsetHeight
;
1321 // Reattach all children
1322 for ( i
= 0, len
= nodes
.length
; i
< len
; i
++ ) {
1323 el
.appendChild( nodes
[ i
] );
1325 // Restore scroll position (no-op if scrollbars disappeared)
1326 el
.scrollLeft
= scrollLeft
;
1327 el
.scrollTop
= scrollTop
;
1333 * Toggle visibility of an element.
1335 * @param {boolean} [show] Make element visible, omit to toggle visibility
1339 OO
.ui
.Element
.prototype.toggle = function ( show
) {
1340 show
= show
=== undefined ? !this.visible
: !!show
;
1342 if ( show
!== this.isVisible() ) {
1343 this.visible
= show
;
1344 this.$element
.toggleClass( 'oo-ui-element-hidden', !this.visible
);
1345 this.emit( 'toggle', show
);
1352 * Check if element is visible.
1354 * @return {boolean} element is visible
1356 OO
.ui
.Element
.prototype.isVisible = function () {
1357 return this.visible
;
1363 * @return {Mixed} Element data
1365 OO
.ui
.Element
.prototype.getData = function () {
1372 * @param {Mixed} data Element data
1375 OO
.ui
.Element
.prototype.setData = function ( data
) {
1381 * Set the element has an 'id' attribute.
1383 * @param {string} id
1386 OO
.ui
.Element
.prototype.setElementId = function ( id
) {
1387 this.elementId
= id
;
1388 this.$element
.attr( 'id', id
);
1393 * Ensure that the element has an 'id' attribute, setting it to an unique value if it's missing,
1394 * and return its value.
1398 OO
.ui
.Element
.prototype.getElementId = function () {
1399 if ( this.elementId
=== null ) {
1400 this.setElementId( OO
.ui
.generateElementId() );
1402 return this.elementId
;
1406 * Check if element supports one or more methods.
1408 * @param {string|string[]} methods Method or list of methods to check
1409 * @return {boolean} All methods are supported
1411 OO
.ui
.Element
.prototype.supports = function ( methods
) {
1415 methods
= Array
.isArray( methods
) ? methods
: [ methods
];
1416 for ( i
= 0, len
= methods
.length
; i
< len
; i
++ ) {
1417 if ( $.isFunction( this[ methods
[ i
] ] ) ) {
1422 return methods
.length
=== support
;
1426 * Update the theme-provided classes.
1428 * @localdoc This is called in element mixins and widget classes any time state changes.
1429 * Updating is debounced, minimizing overhead of changing multiple attributes and
1430 * guaranteeing that theme updates do not occur within an element's constructor
1432 OO
.ui
.Element
.prototype.updateThemeClasses = function () {
1433 OO
.ui
.theme
.queueUpdateElementClasses( this );
1437 * Get the HTML tag name.
1439 * Override this method to base the result on instance information.
1441 * @return {string} HTML tag name
1443 OO
.ui
.Element
.prototype.getTagName = function () {
1444 return this.constructor.static.tagName
;
1448 * Check if the element is attached to the DOM
1450 * @return {boolean} The element is attached to the DOM
1452 OO
.ui
.Element
.prototype.isElementAttached = function () {
1453 return $.contains( this.getElementDocument(), this.$element
[ 0 ] );
1457 * Get the DOM document.
1459 * @return {HTMLDocument} Document object
1461 OO
.ui
.Element
.prototype.getElementDocument = function () {
1462 // Don't cache this in other ways either because subclasses could can change this.$element
1463 return OO
.ui
.Element
.static.getDocument( this.$element
);
1467 * Get the DOM window.
1469 * @return {Window} Window object
1471 OO
.ui
.Element
.prototype.getElementWindow = function () {
1472 return OO
.ui
.Element
.static.getWindow( this.$element
);
1476 * Get closest scrollable container.
1478 * @return {HTMLElement} Closest scrollable container
1480 OO
.ui
.Element
.prototype.getClosestScrollableElementContainer = function () {
1481 return OO
.ui
.Element
.static.getClosestScrollableContainer( this.$element
[ 0 ] );
1485 * Get group element is in.
1487 * @return {OO.ui.mixin.GroupElement|null} Group element, null if none
1489 OO
.ui
.Element
.prototype.getElementGroup = function () {
1490 return this.elementGroup
;
1494 * Set group element is in.
1496 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
1499 OO
.ui
.Element
.prototype.setElementGroup = function ( group
) {
1500 this.elementGroup
= group
;
1505 * Scroll element into view.
1507 * @param {Object} [config] Configuration options
1508 * @return {jQuery.Promise} Promise which resolves when the scroll is complete
1510 OO
.ui
.Element
.prototype.scrollElementIntoView = function ( config
) {
1512 !this.isElementAttached() ||
1513 !this.isVisible() ||
1514 ( this.getElementGroup() && !this.getElementGroup().isVisible() )
1516 return $.Deferred().resolve();
1518 return OO
.ui
.Element
.static.scrollIntoView( this.$element
[ 0 ], config
);
1522 * Restore the pre-infusion dynamic state for this widget.
1524 * This method is called after #$element has been inserted into DOM. The parameter is the return
1525 * value of #gatherPreInfuseState.
1528 * @param {Object} state
1530 OO
.ui
.Element
.prototype.restorePreInfuseState = function () {
1534 * Wraps an HTML snippet for use with configuration values which default
1535 * to strings. This bypasses the default html-escaping done to string
1541 * @param {string} [content] HTML content
1543 OO
.ui
.HtmlSnippet
= function OoUiHtmlSnippet( content
) {
1545 this.content
= content
;
1550 OO
.initClass( OO
.ui
.HtmlSnippet
);
1557 * @return {string} Unchanged HTML snippet.
1559 OO
.ui
.HtmlSnippet
.prototype.toString = function () {
1560 return this.content
;
1564 * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way
1565 * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined.
1566 * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout},
1567 * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout},
1568 * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples.
1572 * @extends OO.ui.Element
1573 * @mixins OO.EventEmitter
1576 * @param {Object} [config] Configuration options
1578 OO
.ui
.Layout
= function OoUiLayout( config
) {
1579 // Configuration initialization
1580 config
= config
|| {};
1582 // Parent constructor
1583 OO
.ui
.Layout
.parent
.call( this, config
);
1585 // Mixin constructors
1586 OO
.EventEmitter
.call( this );
1589 this.$element
.addClass( 'oo-ui-layout' );
1594 OO
.inheritClass( OO
.ui
.Layout
, OO
.ui
.Element
);
1595 OO
.mixinClass( OO
.ui
.Layout
, OO
.EventEmitter
);
1598 * Widgets are compositions of one or more OOjs UI elements that users can both view
1599 * and interact with. All widgets can be configured and modified via a standard API,
1600 * and their state can change dynamically according to a model.
1604 * @extends OO.ui.Element
1605 * @mixins OO.EventEmitter
1608 * @param {Object} [config] Configuration options
1609 * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their
1610 * appearance reflects this state.
1612 OO
.ui
.Widget
= function OoUiWidget( config
) {
1613 // Initialize config
1614 config
= $.extend( { disabled
: false }, config
);
1616 // Parent constructor
1617 OO
.ui
.Widget
.parent
.call( this, config
);
1619 // Mixin constructors
1620 OO
.EventEmitter
.call( this );
1623 this.disabled
= null;
1624 this.wasDisabled
= null;
1627 this.$element
.addClass( 'oo-ui-widget' );
1628 this.setDisabled( !!config
.disabled
);
1633 OO
.inheritClass( OO
.ui
.Widget
, OO
.ui
.Element
);
1634 OO
.mixinClass( OO
.ui
.Widget
, OO
.EventEmitter
);
1641 * A 'disable' event is emitted when the disabled state of the widget changes
1642 * (i.e. on disable **and** enable).
1644 * @param {boolean} disabled Widget is disabled
1650 * A 'toggle' event is emitted when the visibility of the widget changes.
1652 * @param {boolean} visible Widget is visible
1658 * Check if the widget is disabled.
1660 * @return {boolean} Widget is disabled
1662 OO
.ui
.Widget
.prototype.isDisabled = function () {
1663 return this.disabled
;
1667 * Set the 'disabled' state of the widget.
1669 * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state.
1671 * @param {boolean} disabled Disable widget
1674 OO
.ui
.Widget
.prototype.setDisabled = function ( disabled
) {
1677 this.disabled
= !!disabled
;
1678 isDisabled
= this.isDisabled();
1679 if ( isDisabled
!== this.wasDisabled
) {
1680 this.$element
.toggleClass( 'oo-ui-widget-disabled', isDisabled
);
1681 this.$element
.toggleClass( 'oo-ui-widget-enabled', !isDisabled
);
1682 this.$element
.attr( 'aria-disabled', isDisabled
.toString() );
1683 this.emit( 'disable', isDisabled
);
1684 this.updateThemeClasses();
1686 this.wasDisabled
= isDisabled
;
1692 * Update the disabled state, in case of changes in parent widget.
1696 OO
.ui
.Widget
.prototype.updateDisabled = function () {
1697 this.setDisabled( this.disabled
);
1702 * Get an ID of a labelable node which is part of this widget, if any, to be used for `<label for>`
1705 * If this function returns null, the widget should have a meaningful #simulateLabelClick method
1708 * @return {string|null} The ID of the labelable element
1710 OO
.ui
.Widget
.prototype.getInputId = function () {
1715 * Simulate the behavior of clicking on a label (a HTML `<label>` element) bound to this input.
1716 * HTML only allows `<label>` to act on specific "labelable" elements; complex widgets might need to
1717 * override this method to provide intuitive, accessible behavior.
1719 * By default, this does nothing. OO.ui.mixin.TabIndexedElement overrides it for focusable widgets.
1720 * Individual widgets may override it too.
1722 * This method is called by OO.ui.LabelWidget and OO.ui.FieldLayout. It should not be called
1725 OO
.ui
.Widget
.prototype.simulateLabelClick = function () {
1736 OO
.ui
.Theme
= function OoUiTheme() {
1737 this.elementClassesQueue
= [];
1738 this.debouncedUpdateQueuedElementClasses
= OO
.ui
.debounce( this.updateQueuedElementClasses
);
1743 OO
.initClass( OO
.ui
.Theme
);
1748 * Get a list of classes to be applied to a widget.
1750 * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes,
1751 * otherwise state transitions will not work properly.
1753 * @param {OO.ui.Element} element Element for which to get classes
1754 * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists
1756 OO
.ui
.Theme
.prototype.getElementClasses = function () {
1757 return { on
: [], off
: [] };
1761 * Update CSS classes provided by the theme.
1763 * For elements with theme logic hooks, this should be called any time there's a state change.
1765 * @param {OO.ui.Element} element Element for which to update classes
1767 OO
.ui
.Theme
.prototype.updateElementClasses = function ( element
) {
1768 var $elements
= $( [] ),
1769 classes
= this.getElementClasses( element
);
1771 if ( element
.$icon
) {
1772 $elements
= $elements
.add( element
.$icon
);
1774 if ( element
.$indicator
) {
1775 $elements
= $elements
.add( element
.$indicator
);
1779 .removeClass( classes
.off
.join( ' ' ) )
1780 .addClass( classes
.on
.join( ' ' ) );
1786 OO
.ui
.Theme
.prototype.updateQueuedElementClasses = function () {
1788 for ( i
= 0; i
< this.elementClassesQueue
.length
; i
++ ) {
1789 this.updateElementClasses( this.elementClassesQueue
[ i
] );
1792 this.elementClassesQueue
= [];
1796 * Queue #updateElementClasses to be called for this element.
1798 * @localdoc QUnit tests override this method to directly call #queueUpdateElementClasses,
1799 * to make them synchronous.
1801 * @param {OO.ui.Element} element Element for which to update classes
1803 OO
.ui
.Theme
.prototype.queueUpdateElementClasses = function ( element
) {
1804 // Keep items in the queue unique. Use lastIndexOf to start checking from the end because that's
1805 // the most common case (this method is often called repeatedly for the same element).
1806 if ( this.elementClassesQueue
.lastIndexOf( element
) !== -1 ) {
1809 this.elementClassesQueue
.push( element
);
1810 this.debouncedUpdateQueuedElementClasses();
1814 * Get the transition duration in milliseconds for dialogs opening/closing
1816 * The dialog should be fully rendered this many milliseconds after the
1817 * ready process has executed.
1819 * @return {number} Transition duration in milliseconds
1821 OO
.ui
.Theme
.prototype.getDialogTransitionDuration = function () {
1826 * The TabIndexedElement class is an attribute mixin used to add additional functionality to an
1827 * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the
1828 * order in which users will navigate through the focusable elements via the "tab" key.
1831 * // TabIndexedElement is mixed into the ButtonWidget class
1832 * // to provide a tabIndex property.
1833 * var button1 = new OO.ui.ButtonWidget( {
1837 * var button2 = new OO.ui.ButtonWidget( {
1841 * var button3 = new OO.ui.ButtonWidget( {
1845 * var button4 = new OO.ui.ButtonWidget( {
1849 * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element );
1855 * @param {Object} [config] Configuration options
1856 * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default,
1857 * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex
1858 * functionality will be applied to it instead.
1859 * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation
1860 * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1
1861 * to remove the element from the tab-navigation flow.
1863 OO
.ui
.mixin
.TabIndexedElement
= function OoUiMixinTabIndexedElement( config
) {
1864 // Configuration initialization
1865 config
= $.extend( { tabIndex
: 0 }, config
);
1868 this.$tabIndexed
= null;
1869 this.tabIndex
= null;
1872 this.connect( this, { disable
: 'onTabIndexedElementDisable' } );
1875 this.setTabIndex( config
.tabIndex
);
1876 this.setTabIndexedElement( config
.$tabIndexed
|| this.$element
);
1881 OO
.initClass( OO
.ui
.mixin
.TabIndexedElement
);
1886 * Set the element that should use the tabindex functionality.
1888 * This method is used to retarget a tabindex mixin so that its functionality applies
1889 * to the specified element. If an element is currently using the functionality, the mixin’s
1890 * effect on that element is removed before the new element is set up.
1892 * @param {jQuery} $tabIndexed Element that should use the tabindex functionality
1895 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndexedElement = function ( $tabIndexed
) {
1896 var tabIndex
= this.tabIndex
;
1897 // Remove attributes from old $tabIndexed
1898 this.setTabIndex( null );
1899 // Force update of new $tabIndexed
1900 this.$tabIndexed
= $tabIndexed
;
1901 this.tabIndex
= tabIndex
;
1902 return this.updateTabIndex();
1906 * Set the value of the tabindex.
1908 * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex
1911 OO
.ui
.mixin
.TabIndexedElement
.prototype.setTabIndex = function ( tabIndex
) {
1912 tabIndex
= typeof tabIndex
=== 'number' ? tabIndex
: null;
1914 if ( this.tabIndex
!== tabIndex
) {
1915 this.tabIndex
= tabIndex
;
1916 this.updateTabIndex();
1923 * Update the `tabindex` attribute, in case of changes to tab index or
1929 OO
.ui
.mixin
.TabIndexedElement
.prototype.updateTabIndex = function () {
1930 if ( this.$tabIndexed
) {
1931 if ( this.tabIndex
!== null ) {
1932 // Do not index over disabled elements
1933 this.$tabIndexed
.attr( {
1934 tabindex
: this.isDisabled() ? -1 : this.tabIndex
,
1935 // Support: ChromeVox and NVDA
1936 // These do not seem to inherit aria-disabled from parent elements
1937 'aria-disabled': this.isDisabled().toString()
1940 this.$tabIndexed
.removeAttr( 'tabindex aria-disabled' );
1947 * Handle disable events.
1950 * @param {boolean} disabled Element is disabled
1952 OO
.ui
.mixin
.TabIndexedElement
.prototype.onTabIndexedElementDisable = function () {
1953 this.updateTabIndex();
1957 * Get the value of the tabindex.
1959 * @return {number|null} Tabindex value
1961 OO
.ui
.mixin
.TabIndexedElement
.prototype.getTabIndex = function () {
1962 return this.tabIndex
;
1966 * Get an ID of a focusable element of this widget, if any, to be used for `<label for>` value.
1968 * If the element already has an ID then that is returned, otherwise unique ID is
1969 * generated, set on the element, and returned.
1971 * @return {string|null} The ID of the focusable element
1973 OO
.ui
.mixin
.TabIndexedElement
.prototype.getInputId = function () {
1976 if ( !this.$tabIndexed
) {
1979 if ( !this.isLabelableNode( this.$tabIndexed
) ) {
1983 id
= this.$tabIndexed
.attr( 'id' );
1984 if ( id
=== undefined ) {
1985 id
= OO
.ui
.generateElementId();
1986 this.$tabIndexed
.attr( 'id', id
);
1993 * Whether the node is 'labelable' according to the HTML spec
1994 * (i.e., whether it can be interacted with through a `<label for="…">`).
1995 * See: <https://html.spec.whatwg.org/multipage/forms.html#category-label>.
1998 * @param {jQuery} $node
2001 OO
.ui
.mixin
.TabIndexedElement
.prototype.isLabelableNode = function ( $node
) {
2003 labelableTags
= [ 'button', 'meter', 'output', 'progress', 'select', 'textarea' ],
2004 tagName
= $node
.prop( 'tagName' ).toLowerCase();
2006 if ( tagName
=== 'input' && $node
.attr( 'type' ) !== 'hidden' ) {
2009 if ( labelableTags
.indexOf( tagName
) !== -1 ) {
2016 * Focus this element.
2020 OO
.ui
.mixin
.TabIndexedElement
.prototype.focus = function () {
2021 if ( !this.isDisabled() ) {
2022 this.$tabIndexed
.focus();
2028 * Blur this element.
2032 OO
.ui
.mixin
.TabIndexedElement
.prototype.blur = function () {
2033 this.$tabIndexed
.blur();
2038 * @inheritdoc OO.ui.Widget
2040 OO
.ui
.mixin
.TabIndexedElement
.prototype.simulateLabelClick = function () {
2045 * ButtonElement is often mixed into other classes to generate a button, which is a clickable
2046 * interface element that can be configured with access keys for accessibility.
2047 * See the [OOjs UI documentation on MediaWiki] [1] for examples.
2049 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons
2055 * @param {Object} [config] Configuration options
2056 * @cfg {jQuery} [$button] The button element created by the class.
2057 * If this configuration is omitted, the button element will use a generated `<a>`.
2058 * @cfg {boolean} [framed=true] Render the button with a frame
2060 OO
.ui
.mixin
.ButtonElement
= function OoUiMixinButtonElement( config
) {
2061 // Configuration initialization
2062 config
= config
|| {};
2065 this.$button
= null;
2067 this.active
= config
.active
!== undefined && config
.active
;
2068 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
2069 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
2070 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
2071 this.onKeyUpHandler
= this.onKeyUp
.bind( this );
2072 this.onClickHandler
= this.onClick
.bind( this );
2073 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
2076 this.$element
.addClass( 'oo-ui-buttonElement' );
2077 this.toggleFramed( config
.framed
=== undefined || config
.framed
);
2078 this.setButtonElement( config
.$button
|| $( '<a>' ) );
2083 OO
.initClass( OO
.ui
.mixin
.ButtonElement
);
2085 /* Static Properties */
2088 * Cancel mouse down events.
2090 * This property is usually set to `true` to prevent the focus from changing when the button is clicked.
2091 * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget}
2092 * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a
2097 * @property {boolean}
2099 OO
.ui
.mixin
.ButtonElement
.static.cancelButtonMouseDownEvents
= true;
2104 * A 'click' event is emitted when the button element is clicked.
2112 * Set the button element.
2114 * This method is used to retarget a button mixin so that its functionality applies to
2115 * the specified button element instead of the one created by the class. If a button element
2116 * is already set, the method will remove the mixin’s effect on that element.
2118 * @param {jQuery} $button Element to use as button
2120 OO
.ui
.mixin
.ButtonElement
.prototype.setButtonElement = function ( $button
) {
2121 if ( this.$button
) {
2123 .removeClass( 'oo-ui-buttonElement-button' )
2124 .removeAttr( 'role accesskey' )
2126 mousedown
: this.onMouseDownHandler
,
2127 keydown
: this.onKeyDownHandler
,
2128 click
: this.onClickHandler
,
2129 keypress
: this.onKeyPressHandler
2133 this.$button
= $button
2134 .addClass( 'oo-ui-buttonElement-button' )
2136 mousedown
: this.onMouseDownHandler
,
2137 keydown
: this.onKeyDownHandler
,
2138 click
: this.onClickHandler
,
2139 keypress
: this.onKeyPressHandler
2142 // Add `role="button"` on `<a>` elements, where it's needed
2143 // `toUppercase()` is added for XHTML documents
2144 if ( this.$button
.prop( 'tagName' ).toUpperCase() === 'A' ) {
2145 this.$button
.attr( 'role', 'button' );
2150 * Handles mouse down events.
2153 * @param {jQuery.Event} e Mouse down event
2155 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseDown = function ( e
) {
2156 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2159 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2160 // Run the mouseup handler no matter where the mouse is when the button is let go, so we can
2161 // reliably remove the pressed class
2162 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
2163 // Prevent change of focus unless specifically configured otherwise
2164 if ( this.constructor.static.cancelButtonMouseDownEvents
) {
2170 * Handles mouse up events.
2173 * @param {MouseEvent} e Mouse up event
2175 OO
.ui
.mixin
.ButtonElement
.prototype.onMouseUp = function ( e
) {
2176 if ( this.isDisabled() || e
.which
!== OO
.ui
.MouseButtons
.LEFT
) {
2179 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2180 // Stop listening for mouseup, since we only needed this once
2181 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
2185 * Handles mouse click events.
2188 * @param {jQuery.Event} e Mouse click event
2191 OO
.ui
.mixin
.ButtonElement
.prototype.onClick = function ( e
) {
2192 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
2193 if ( this.emit( 'click' ) ) {
2200 * Handles key down events.
2203 * @param {jQuery.Event} e Key down event
2205 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyDown = function ( e
) {
2206 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2209 this.$element
.addClass( 'oo-ui-buttonElement-pressed' );
2210 // Run the keyup handler no matter where the key is when the button is let go, so we can
2211 // reliably remove the pressed class
2212 this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler
, true );
2216 * Handles key up events.
2219 * @param {KeyboardEvent} e Key up event
2221 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyUp = function ( e
) {
2222 if ( this.isDisabled() || ( e
.which
!== OO
.ui
.Keys
.SPACE
&& e
.which
!== OO
.ui
.Keys
.ENTER
) ) {
2225 this.$element
.removeClass( 'oo-ui-buttonElement-pressed' );
2226 // Stop listening for keyup, since we only needed this once
2227 this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler
, true );
2231 * Handles key press events.
2234 * @param {jQuery.Event} e Key press event
2237 OO
.ui
.mixin
.ButtonElement
.prototype.onKeyPress = function ( e
) {
2238 if ( !this.isDisabled() && ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
) ) {
2239 if ( this.emit( 'click' ) ) {
2246 * Check if button has a frame.
2248 * @return {boolean} Button is framed
2250 OO
.ui
.mixin
.ButtonElement
.prototype.isFramed = function () {
2255 * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off.
2257 * @param {boolean} [framed] Make button framed, omit to toggle
2260 OO
.ui
.mixin
.ButtonElement
.prototype.toggleFramed = function ( framed
) {
2261 framed
= framed
=== undefined ? !this.framed
: !!framed
;
2262 if ( framed
!== this.framed
) {
2263 this.framed
= framed
;
2265 .toggleClass( 'oo-ui-buttonElement-frameless', !framed
)
2266 .toggleClass( 'oo-ui-buttonElement-framed', framed
);
2267 this.updateThemeClasses();
2274 * Set the button's active state.
2276 * The active state can be set on:
2278 * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected
2279 * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on
2280 * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page
2283 * @param {boolean} value Make button active
2286 OO
.ui
.mixin
.ButtonElement
.prototype.setActive = function ( value
) {
2287 this.active
= !!value
;
2288 this.$element
.toggleClass( 'oo-ui-buttonElement-active', this.active
);
2289 this.updateThemeClasses();
2294 * Check if the button is active
2297 * @return {boolean} The button is active
2299 OO
.ui
.mixin
.ButtonElement
.prototype.isActive = function () {
2304 * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or
2305 * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing
2306 * items from the group is done through the interface the class provides.
2307 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
2309 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups
2312 * @mixins OO.EmitterList
2316 * @param {Object} [config] Configuration options
2317 * @cfg {jQuery} [$group] The container element created by the class. If this configuration
2318 * is omitted, the group element will use a generated `<div>`.
2320 OO
.ui
.mixin
.GroupElement
= function OoUiMixinGroupElement( config
) {
2321 // Configuration initialization
2322 config
= config
|| {};
2324 // Mixin constructors
2325 OO
.EmitterList
.call( this, config
);
2331 this.setGroupElement( config
.$group
|| $( '<div>' ) );
2336 OO
.mixinClass( OO
.ui
.mixin
.GroupElement
, OO
.EmitterList
);
2343 * A change event is emitted when the set of selected items changes.
2345 * @param {OO.ui.Element[]} items Items currently in the group
2351 * Set the group element.
2353 * If an element is already set, items will be moved to the new element.
2355 * @param {jQuery} $group Element to use as group
2357 OO
.ui
.mixin
.GroupElement
.prototype.setGroupElement = function ( $group
) {
2360 this.$group
= $group
;
2361 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2362 this.$group
.append( this.items
[ i
].$element
);
2367 * Get an item by its data.
2369 * Only the first item with matching data will be returned. To return all matching items,
2370 * use the #getItemsFromData method.
2372 * @param {Object} data Item data to search for
2373 * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists
2375 OO
.ui
.mixin
.GroupElement
.prototype.getItemFromData = function ( data
) {
2377 hash
= OO
.getHash( data
);
2379 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2380 item
= this.items
[ i
];
2381 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2390 * Get items by their data.
2392 * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead.
2394 * @param {Object} data Item data to search for
2395 * @return {OO.ui.Element[]} Items with equivalent data
2397 OO
.ui
.mixin
.GroupElement
.prototype.getItemsFromData = function ( data
) {
2399 hash
= OO
.getHash( data
),
2402 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2403 item
= this.items
[ i
];
2404 if ( hash
=== OO
.getHash( item
.getData() ) ) {
2413 * Add items to the group.
2415 * Items will be added to the end of the group array unless the optional `index` parameter specifies
2416 * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`.
2418 * @param {OO.ui.Element[]} items An array of items to add to the group
2419 * @param {number} [index] Index of the insertion point
2422 OO
.ui
.mixin
.GroupElement
.prototype.addItems = function ( items
, index
) {
2424 OO
.EmitterList
.prototype.addItems
.call( this, items
, index
);
2426 this.emit( 'change', this.getItems() );
2433 OO
.ui
.mixin
.GroupElement
.prototype.moveItem = function ( items
, newIndex
) {
2434 // insertItemElements expects this.items to not have been modified yet, so call before the mixin
2435 this.insertItemElements( items
, newIndex
);
2438 newIndex
= OO
.EmitterList
.prototype.moveItem
.call( this, items
, newIndex
);
2446 OO
.ui
.mixin
.GroupElement
.prototype.insertItem = function ( item
, index
) {
2447 item
.setElementGroup( this );
2448 this.insertItemElements( item
, index
);
2451 index
= OO
.EmitterList
.prototype.insertItem
.call( this, item
, index
);
2457 * Insert elements into the group
2460 * @param {OO.ui.Element} itemWidget Item to insert
2461 * @param {number} index Insertion index
2463 OO
.ui
.mixin
.GroupElement
.prototype.insertItemElements = function ( itemWidget
, index
) {
2464 if ( index
=== undefined || index
< 0 || index
>= this.items
.length
) {
2465 this.$group
.append( itemWidget
.$element
);
2466 } else if ( index
=== 0 ) {
2467 this.$group
.prepend( itemWidget
.$element
);
2469 this.items
[ index
].$element
.before( itemWidget
.$element
);
2474 * Remove the specified items from a group.
2476 * Removed items are detached (not removed) from the DOM so that they may be reused.
2477 * To remove all items from a group, you may wish to use the #clearItems method instead.
2479 * @param {OO.ui.Element[]} items An array of items to remove
2482 OO
.ui
.mixin
.GroupElement
.prototype.removeItems = function ( items
) {
2483 var i
, len
, item
, index
;
2485 // Remove specific items elements
2486 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
2488 index
= this.items
.indexOf( item
);
2489 if ( index
!== -1 ) {
2490 item
.setElementGroup( null );
2491 item
.$element
.detach();
2496 OO
.EmitterList
.prototype.removeItems
.call( this, items
);
2498 this.emit( 'change', this.getItems() );
2503 * Clear all items from the group.
2505 * Cleared items are detached from the DOM, not removed, so that they may be reused.
2506 * To remove only a subset of items from a group, use the #removeItems method.
2510 OO
.ui
.mixin
.GroupElement
.prototype.clearItems = function () {
2513 // Remove all item elements
2514 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
2515 this.items
[ i
].setElementGroup( null );
2516 this.items
[ i
].$element
.detach();
2520 OO
.EmitterList
.prototype.clearItems
.call( this );
2522 this.emit( 'change', this.getItems() );
2527 * IconElement is often mixed into other classes to generate an icon.
2528 * Icons are graphics, about the size of normal text. They are used to aid the user
2529 * in locating a control or to convey information in a space-efficient way. See the
2530 * [OOjs UI documentation on MediaWiki] [1] for a list of icons
2531 * included in the library.
2533 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2539 * @param {Object} [config] Configuration options
2540 * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted,
2541 * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that
2542 * the icon element be set to an existing icon instead of the one generated by this class, set a
2543 * value using a jQuery selection. For example:
2545 * // Use a <div> tag instead of a <span>
2547 * // Use an existing icon element instead of the one generated by the class
2548 * $icon: this.$element
2549 * // Use an icon element from a child widget
2550 * $icon: this.childwidget.$element
2551 * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of
2552 * symbolic names. A map is used for i18n purposes and contains a `default` icon
2553 * name and additional names keyed by language code. The `default` name is used when no icon is keyed
2554 * by the user's language.
2556 * Example of an i18n map:
2558 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2559 * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library.
2560 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
2561 * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title
2562 * text. The icon title is displayed when users move the mouse over the icon.
2564 OO
.ui
.mixin
.IconElement
= function OoUiMixinIconElement( config
) {
2565 // Configuration initialization
2566 config
= config
|| {};
2571 this.iconTitle
= null;
2574 this.setIcon( config
.icon
|| this.constructor.static.icon
);
2575 this.setIconTitle( config
.iconTitle
|| this.constructor.static.iconTitle
);
2576 this.setIconElement( config
.$icon
|| $( '<span>' ) );
2581 OO
.initClass( OO
.ui
.mixin
.IconElement
);
2583 /* Static Properties */
2586 * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used
2587 * for i18n purposes and contains a `default` icon name and additional names keyed by
2588 * language code. The `default` name is used when no icon is keyed by the user's language.
2590 * Example of an i18n map:
2592 * { default: 'bold-a', en: 'bold-b', de: 'bold-f' }
2594 * Note: the static property will be overridden if the #icon configuration is used.
2598 * @property {Object|string}
2600 OO
.ui
.mixin
.IconElement
.static.icon
= null;
2603 * The icon title, displayed when users move the mouse over the icon. The value can be text, a
2604 * function that returns title text, or `null` for no title.
2606 * The static property will be overridden if the #iconTitle configuration is used.
2610 * @property {string|Function|null}
2612 OO
.ui
.mixin
.IconElement
.static.iconTitle
= null;
2617 * Set the icon element. This method is used to retarget an icon mixin so that its functionality
2618 * applies to the specified icon element instead of the one created by the class. If an icon
2619 * element is already set, the mixin’s effect on that element is removed. Generated CSS classes
2620 * and mixin methods will no longer affect the element.
2622 * @param {jQuery} $icon Element to use as icon
2624 OO
.ui
.mixin
.IconElement
.prototype.setIconElement = function ( $icon
) {
2627 .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon
)
2628 .removeAttr( 'title' );
2632 .addClass( 'oo-ui-iconElement-icon' )
2633 .toggleClass( 'oo-ui-icon-' + this.icon
, !!this.icon
);
2634 if ( this.iconTitle
!== null ) {
2635 this.$icon
.attr( 'title', this.iconTitle
);
2638 this.updateThemeClasses();
2642 * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon.
2643 * The icon parameter can also be set to a map of icon names. See the #icon config setting
2646 * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed
2647 * by language code, or `null` to remove the icon.
2650 OO
.ui
.mixin
.IconElement
.prototype.setIcon = function ( icon
) {
2651 icon
= OO
.isPlainObject( icon
) ? OO
.ui
.getLocalValue( icon
, null, 'default' ) : icon
;
2652 icon
= typeof icon
=== 'string' && icon
.trim().length
? icon
.trim() : null;
2654 if ( this.icon
!== icon
) {
2656 if ( this.icon
!== null ) {
2657 this.$icon
.removeClass( 'oo-ui-icon-' + this.icon
);
2659 if ( icon
!== null ) {
2660 this.$icon
.addClass( 'oo-ui-icon-' + icon
);
2666 this.$element
.toggleClass( 'oo-ui-iconElement', !!this.icon
);
2667 this.updateThemeClasses();
2673 * Set the icon title. Use `null` to remove the title.
2675 * @param {string|Function|null} iconTitle A text string used as the icon title,
2676 * a function that returns title text, or `null` for no title.
2679 OO
.ui
.mixin
.IconElement
.prototype.setIconTitle = function ( iconTitle
) {
2680 iconTitle
= typeof iconTitle
=== 'function' ||
2681 ( typeof iconTitle
=== 'string' && iconTitle
.length
) ?
2682 OO
.ui
.resolveMsg( iconTitle
) : null;
2684 if ( this.iconTitle
!== iconTitle
) {
2685 this.iconTitle
= iconTitle
;
2687 if ( this.iconTitle
!== null ) {
2688 this.$icon
.attr( 'title', iconTitle
);
2690 this.$icon
.removeAttr( 'title' );
2699 * Get the symbolic name of the icon.
2701 * @return {string} Icon name
2703 OO
.ui
.mixin
.IconElement
.prototype.getIcon = function () {
2708 * Get the icon title. The title text is displayed when a user moves the mouse over the icon.
2710 * @return {string} Icon title text
2712 OO
.ui
.mixin
.IconElement
.prototype.getIconTitle = function () {
2713 return this.iconTitle
;
2717 * IndicatorElement is often mixed into other classes to generate an indicator.
2718 * Indicators are small graphics that are generally used in two ways:
2720 * - To draw attention to the status of an item. For example, an indicator might be
2721 * used to show that an item in a list has errors that need to be resolved.
2722 * - To clarify the function of a control that acts in an exceptional way (a button
2723 * that opens a menu instead of performing an action directly, for example).
2725 * For a list of indicators included in the library, please see the
2726 * [OOjs UI documentation on MediaWiki] [1].
2728 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2734 * @param {Object} [config] Configuration options
2735 * @cfg {jQuery} [$indicator] The indicator element created by the class. If this
2736 * configuration is omitted, the indicator element will use a generated `<span>`.
2737 * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2738 * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included
2740 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
2741 * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title,
2742 * or a function that returns title text. The indicator title is displayed when users move
2743 * the mouse over the indicator.
2745 OO
.ui
.mixin
.IndicatorElement
= function OoUiMixinIndicatorElement( config
) {
2746 // Configuration initialization
2747 config
= config
|| {};
2750 this.$indicator
= null;
2751 this.indicator
= null;
2752 this.indicatorTitle
= null;
2755 this.setIndicator( config
.indicator
|| this.constructor.static.indicator
);
2756 this.setIndicatorTitle( config
.indicatorTitle
|| this.constructor.static.indicatorTitle
);
2757 this.setIndicatorElement( config
.$indicator
|| $( '<span>' ) );
2762 OO
.initClass( OO
.ui
.mixin
.IndicatorElement
);
2764 /* Static Properties */
2767 * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2768 * The static property will be overridden if the #indicator configuration is used.
2772 * @property {string|null}
2774 OO
.ui
.mixin
.IndicatorElement
.static.indicator
= null;
2777 * A text string used as the indicator title, a function that returns title text, or `null`
2778 * for no title. The static property will be overridden if the #indicatorTitle configuration is used.
2782 * @property {string|Function|null}
2784 OO
.ui
.mixin
.IndicatorElement
.static.indicatorTitle
= null;
2789 * Set the indicator element.
2791 * If an element is already set, it will be cleaned up before setting up the new element.
2793 * @param {jQuery} $indicator Element to use as indicator
2795 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorElement = function ( $indicator
) {
2796 if ( this.$indicator
) {
2798 .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator
)
2799 .removeAttr( 'title' );
2802 this.$indicator
= $indicator
2803 .addClass( 'oo-ui-indicatorElement-indicator' )
2804 .toggleClass( 'oo-ui-indicator-' + this.indicator
, !!this.indicator
);
2805 if ( this.indicatorTitle
!== null ) {
2806 this.$indicator
.attr( 'title', this.indicatorTitle
);
2809 this.updateThemeClasses();
2813 * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator.
2815 * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator
2818 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicator = function ( indicator
) {
2819 indicator
= typeof indicator
=== 'string' && indicator
.length
? indicator
.trim() : null;
2821 if ( this.indicator
!== indicator
) {
2822 if ( this.$indicator
) {
2823 if ( this.indicator
!== null ) {
2824 this.$indicator
.removeClass( 'oo-ui-indicator-' + this.indicator
);
2826 if ( indicator
!== null ) {
2827 this.$indicator
.addClass( 'oo-ui-indicator-' + indicator
);
2830 this.indicator
= indicator
;
2833 this.$element
.toggleClass( 'oo-ui-indicatorElement', !!this.indicator
);
2834 this.updateThemeClasses();
2840 * Set the indicator title.
2842 * The title is displayed when a user moves the mouse over the indicator.
2844 * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or
2845 * `null` for no indicator title
2848 OO
.ui
.mixin
.IndicatorElement
.prototype.setIndicatorTitle = function ( indicatorTitle
) {
2849 indicatorTitle
= typeof indicatorTitle
=== 'function' ||
2850 ( typeof indicatorTitle
=== 'string' && indicatorTitle
.length
) ?
2851 OO
.ui
.resolveMsg( indicatorTitle
) : null;
2853 if ( this.indicatorTitle
!== indicatorTitle
) {
2854 this.indicatorTitle
= indicatorTitle
;
2855 if ( this.$indicator
) {
2856 if ( this.indicatorTitle
!== null ) {
2857 this.$indicator
.attr( 'title', indicatorTitle
);
2859 this.$indicator
.removeAttr( 'title' );
2868 * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’).
2870 * @return {string} Symbolic name of indicator
2872 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicator = function () {
2873 return this.indicator
;
2877 * Get the indicator title.
2879 * The title is displayed when a user moves the mouse over the indicator.
2881 * @return {string} Indicator title text
2883 OO
.ui
.mixin
.IndicatorElement
.prototype.getIndicatorTitle = function () {
2884 return this.indicatorTitle
;
2888 * LabelElement is often mixed into other classes to generate a label, which
2889 * helps identify the function of an interface element.
2890 * See the [OOjs UI documentation on MediaWiki] [1] for more information.
2892 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2898 * @param {Object} [config] Configuration options
2899 * @cfg {jQuery} [$label] The label element created by the class. If this
2900 * configuration is omitted, the label element will use a generated `<span>`.
2901 * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified
2902 * as a plaintext string, a jQuery selection of elements, or a function that will produce a string
2903 * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples.
2904 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels
2906 OO
.ui
.mixin
.LabelElement
= function OoUiMixinLabelElement( config
) {
2907 // Configuration initialization
2908 config
= config
|| {};
2915 this.setLabel( config
.label
|| this.constructor.static.label
);
2916 this.setLabelElement( config
.$label
|| $( '<span>' ) );
2921 OO
.initClass( OO
.ui
.mixin
.LabelElement
);
2926 * @event labelChange
2927 * @param {string} value
2930 /* Static Properties */
2933 * The label text. The label can be specified as a plaintext string, a function that will
2934 * produce a string in the future, or `null` for no label. The static value will
2935 * be overridden if a label is specified with the #label config option.
2939 * @property {string|Function|null}
2941 OO
.ui
.mixin
.LabelElement
.static.label
= null;
2943 /* Static methods */
2946 * Highlight the first occurrence of the query in the given text
2948 * @param {string} text Text
2949 * @param {string} query Query to find
2950 * @return {jQuery} Text with the first match of the query
2951 * sub-string wrapped in highlighted span
2953 OO
.ui
.mixin
.LabelElement
.static.highlightQuery = function ( text
, query
) {
2954 var $result
= $( '<span>' ),
2955 offset
= text
.toLowerCase().indexOf( query
.toLowerCase() );
2957 if ( !query
.length
|| offset
=== -1 ) {
2958 return $result
.text( text
);
2961 document
.createTextNode( text
.slice( 0, offset
) ),
2963 .addClass( 'oo-ui-labelElement-label-highlight' )
2964 .text( text
.slice( offset
, offset
+ query
.length
) ),
2965 document
.createTextNode( text
.slice( offset
+ query
.length
) )
2967 return $result
.contents();
2973 * Set the label element.
2975 * If an element is already set, it will be cleaned up before setting up the new element.
2977 * @param {jQuery} $label Element to use as label
2979 OO
.ui
.mixin
.LabelElement
.prototype.setLabelElement = function ( $label
) {
2980 if ( this.$label
) {
2981 this.$label
.removeClass( 'oo-ui-labelElement-label' ).empty();
2984 this.$label
= $label
.addClass( 'oo-ui-labelElement-label' );
2985 this.setLabelContent( this.label
);
2991 * An empty string will result in the label being hidden. A string containing only whitespace will
2992 * be converted to a single ` `.
2994 * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or
2995 * text; or null for no label
2998 OO
.ui
.mixin
.LabelElement
.prototype.setLabel = function ( label
) {
2999 label
= typeof label
=== 'function' ? OO
.ui
.resolveMsg( label
) : label
;
3000 label
= ( ( typeof label
=== 'string' || label
instanceof jQuery
) && label
.length
) || ( label
instanceof OO
.ui
.HtmlSnippet
&& label
.toString().length
) ? label
: null;
3002 if ( this.label
!== label
) {
3003 if ( this.$label
) {
3004 this.setLabelContent( label
);
3007 this.emit( 'labelChange' );
3010 this.$element
.toggleClass( 'oo-ui-labelElement', !!this.label
);
3016 * Set the label as plain text with a highlighted query
3018 * @param {string} text Text label to set
3019 * @param {string} query Substring of text to highlight
3022 OO
.ui
.mixin
.LabelElement
.prototype.setHighlightedQuery = function ( text
, query
) {
3023 return this.setLabel( this.constructor.static.highlightQuery( text
, query
) );
3029 * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or
3030 * text; or null for no label
3032 OO
.ui
.mixin
.LabelElement
.prototype.getLabel = function () {
3037 * Set the content of the label.
3039 * Do not call this method until after the label element has been set by #setLabelElement.
3042 * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or
3043 * text; or null for no label
3045 OO
.ui
.mixin
.LabelElement
.prototype.setLabelContent = function ( label
) {
3046 if ( typeof label
=== 'string' ) {
3047 if ( label
.match( /^\s*$/ ) ) {
3048 // Convert whitespace only string to a single non-breaking space
3049 this.$label
.html( ' ' );
3051 this.$label
.text( label
);
3053 } else if ( label
instanceof OO
.ui
.HtmlSnippet
) {
3054 this.$label
.html( label
.toString() );
3055 } else if ( label
instanceof jQuery
) {
3056 this.$label
.empty().append( label
);
3058 this.$label
.empty();
3063 * The FlaggedElement class is an attribute mixin, meaning that it is used to add
3064 * additional functionality to an element created by another class. The class provides
3065 * a ‘flags’ property assigned the name (or an array of names) of styling flags,
3066 * which are used to customize the look and feel of a widget to better describe its
3067 * importance and functionality.
3069 * The library currently contains the following styling flags for general use:
3071 * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process.
3072 * - **destructive**: Destructive styling is applied to convey that the widget will remove something.
3073 * - **constructive**: Constructive styling is applied to convey that the widget will create something.
3075 * The flags affect the appearance of the buttons:
3078 * // FlaggedElement is mixed into ButtonWidget to provide styling flags
3079 * var button1 = new OO.ui.ButtonWidget( {
3080 * label: 'Constructive',
3081 * flags: 'constructive'
3083 * var button2 = new OO.ui.ButtonWidget( {
3084 * label: 'Destructive',
3085 * flags: 'destructive'
3087 * var button3 = new OO.ui.ButtonWidget( {
3088 * label: 'Progressive',
3089 * flags: 'progressive'
3091 * $( 'body' ).append( button1.$element, button2.$element, button3.$element );
3093 * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**.
3094 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
3096 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3102 * @param {Object} [config] Configuration options
3103 * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply.
3104 * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags.
3105 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged
3106 * @cfg {jQuery} [$flagged] The flagged element. By default,
3107 * the flagged functionality is applied to the element created by the class ($element).
3108 * If a different element is specified, the flagged functionality will be applied to it instead.
3110 OO
.ui
.mixin
.FlaggedElement
= function OoUiMixinFlaggedElement( config
) {
3111 // Configuration initialization
3112 config
= config
|| {};
3116 this.$flagged
= null;
3119 this.setFlags( config
.flags
);
3120 this.setFlaggedElement( config
.$flagged
|| this.$element
);
3127 * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes`
3128 * parameter contains the name of each modified flag and indicates whether it was
3131 * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates
3132 * that the flag was added, `false` that the flag was removed.
3138 * Set the flagged element.
3140 * This method is used to retarget a flagged mixin so that its functionality applies to the specified element.
3141 * If an element is already set, the method will remove the mixin’s effect on that element.
3143 * @param {jQuery} $flagged Element that should be flagged
3145 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlaggedElement = function ( $flagged
) {
3146 var classNames
= Object
.keys( this.flags
).map( function ( flag
) {
3147 return 'oo-ui-flaggedElement-' + flag
;
3150 if ( this.$flagged
) {
3151 this.$flagged
.removeClass( classNames
);
3154 this.$flagged
= $flagged
.addClass( classNames
);
3158 * Check if the specified flag is set.
3160 * @param {string} flag Name of flag
3161 * @return {boolean} The flag is set
3163 OO
.ui
.mixin
.FlaggedElement
.prototype.hasFlag = function ( flag
) {
3164 // This may be called before the constructor, thus before this.flags is set
3165 return this.flags
&& ( flag
in this.flags
);
3169 * Get the names of all flags set.
3171 * @return {string[]} Flag names
3173 OO
.ui
.mixin
.FlaggedElement
.prototype.getFlags = function () {
3174 // This may be called before the constructor, thus before this.flags is set
3175 return Object
.keys( this.flags
|| {} );
3184 OO
.ui
.mixin
.FlaggedElement
.prototype.clearFlags = function () {
3185 var flag
, className
,
3188 classPrefix
= 'oo-ui-flaggedElement-';
3190 for ( flag
in this.flags
) {
3191 className
= classPrefix
+ flag
;
3192 changes
[ flag
] = false;
3193 delete this.flags
[ flag
];
3194 remove
.push( className
);
3197 if ( this.$flagged
) {
3198 this.$flagged
.removeClass( remove
.join( ' ' ) );
3201 this.updateThemeClasses();
3202 this.emit( 'flag', changes
);
3208 * Add one or more flags.
3210 * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names,
3211 * or an object keyed by flag name with a boolean value that indicates whether the flag should
3212 * be added (`true`) or removed (`false`).
3216 OO
.ui
.mixin
.FlaggedElement
.prototype.setFlags = function ( flags
) {
3217 var i
, len
, flag
, className
,
3221 classPrefix
= 'oo-ui-flaggedElement-';
3223 if ( typeof flags
=== 'string' ) {
3224 className
= classPrefix
+ flags
;
3226 if ( !this.flags
[ flags
] ) {
3227 this.flags
[ flags
] = true;
3228 add
.push( className
);
3230 } else if ( Array
.isArray( flags
) ) {
3231 for ( i
= 0, len
= flags
.length
; i
< len
; i
++ ) {
3233 className
= classPrefix
+ flag
;
3235 if ( !this.flags
[ flag
] ) {
3236 changes
[ flag
] = true;
3237 this.flags
[ flag
] = true;
3238 add
.push( className
);
3241 } else if ( OO
.isPlainObject( flags
) ) {
3242 for ( flag
in flags
) {
3243 className
= classPrefix
+ flag
;
3244 if ( flags
[ flag
] ) {
3246 if ( !this.flags
[ flag
] ) {
3247 changes
[ flag
] = true;
3248 this.flags
[ flag
] = true;
3249 add
.push( className
);
3253 if ( this.flags
[ flag
] ) {
3254 changes
[ flag
] = false;
3255 delete this.flags
[ flag
];
3256 remove
.push( className
);
3262 if ( this.$flagged
) {
3264 .addClass( add
.join( ' ' ) )
3265 .removeClass( remove
.join( ' ' ) );
3268 this.updateThemeClasses();
3269 this.emit( 'flag', changes
);
3275 * TitledElement is mixed into other classes to provide a `title` attribute.
3276 * Titles are rendered by the browser and are made visible when the user moves
3277 * the mouse over the element. Titles are not visible on touch devices.
3280 * // TitledElement provides a 'title' attribute to the
3281 * // ButtonWidget class
3282 * var button = new OO.ui.ButtonWidget( {
3283 * label: 'Button with Title',
3284 * title: 'I am a button'
3286 * $( 'body' ).append( button.$element );
3292 * @param {Object} [config] Configuration options
3293 * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied.
3294 * If this config is omitted, the title functionality is applied to $element, the
3295 * element created by the class.
3296 * @cfg {string|Function} [title] The title text or a function that returns text. If
3297 * this config is omitted, the value of the {@link #static-title static title} property is used.
3299 OO
.ui
.mixin
.TitledElement
= function OoUiMixinTitledElement( config
) {
3300 // Configuration initialization
3301 config
= config
|| {};
3304 this.$titled
= null;
3308 this.setTitle( config
.title
!== undefined ? config
.title
: this.constructor.static.title
);
3309 this.setTitledElement( config
.$titled
|| this.$element
);
3314 OO
.initClass( OO
.ui
.mixin
.TitledElement
);
3316 /* Static Properties */
3319 * The title text, a function that returns text, or `null` for no title. The value of the static property
3320 * is overridden if the #title config option is used.
3324 * @property {string|Function|null}
3326 OO
.ui
.mixin
.TitledElement
.static.title
= null;
3331 * Set the titled element.
3333 * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element.
3334 * If an element is already set, the mixin’s effect on that element is removed before the new element is set up.
3336 * @param {jQuery} $titled Element that should use the 'titled' functionality
3338 OO
.ui
.mixin
.TitledElement
.prototype.setTitledElement = function ( $titled
) {
3339 if ( this.$titled
) {
3340 this.$titled
.removeAttr( 'title' );
3343 this.$titled
= $titled
;
3345 this.$titled
.attr( 'title', this.title
);
3352 * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title
3355 OO
.ui
.mixin
.TitledElement
.prototype.setTitle = function ( title
) {
3356 title
= typeof title
=== 'function' ? OO
.ui
.resolveMsg( title
) : title
;
3357 title
= ( typeof title
=== 'string' && title
.length
) ? title
: null;
3359 if ( this.title
!== title
) {
3360 if ( this.$titled
) {
3361 if ( title
!== null ) {
3362 this.$titled
.attr( 'title', title
);
3364 this.$titled
.removeAttr( 'title' );
3376 * @return {string} Title string
3378 OO
.ui
.mixin
.TitledElement
.prototype.getTitle = function () {
3383 * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute.
3384 * Accesskeys allow an user to go to a specific element by using
3385 * a shortcut combination of a browser specific keys + the key
3389 * // AccessKeyedElement provides an 'accesskey' attribute to the
3390 * // ButtonWidget class
3391 * var button = new OO.ui.ButtonWidget( {
3392 * label: 'Button with Accesskey',
3395 * $( 'body' ).append( button.$element );
3401 * @param {Object} [config] Configuration options
3402 * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied.
3403 * If this config is omitted, the accesskey functionality is applied to $element, the
3404 * element created by the class.
3405 * @cfg {string|Function} [accessKey] The key or a function that returns the key. If
3406 * this config is omitted, no accesskey will be added.
3408 OO
.ui
.mixin
.AccessKeyedElement
= function OoUiMixinAccessKeyedElement( config
) {
3409 // Configuration initialization
3410 config
= config
|| {};
3413 this.$accessKeyed
= null;
3414 this.accessKey
= null;
3417 this.setAccessKey( config
.accessKey
|| null );
3418 this.setAccessKeyedElement( config
.$accessKeyed
|| this.$element
);
3423 OO
.initClass( OO
.ui
.mixin
.AccessKeyedElement
);
3425 /* Static Properties */
3428 * The access key, a function that returns a key, or `null` for no accesskey.
3432 * @property {string|Function|null}
3434 OO
.ui
.mixin
.AccessKeyedElement
.static.accessKey
= null;
3439 * Set the accesskeyed element.
3441 * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element.
3442 * If an element is already set, the mixin's effect on that element is removed before the new element is set up.
3444 * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality
3446 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKeyedElement = function ( $accessKeyed
) {
3447 if ( this.$accessKeyed
) {
3448 this.$accessKeyed
.removeAttr( 'accesskey' );
3451 this.$accessKeyed
= $accessKeyed
;
3452 if ( this.accessKey
) {
3453 this.$accessKeyed
.attr( 'accesskey', this.accessKey
);
3460 * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey
3463 OO
.ui
.mixin
.AccessKeyedElement
.prototype.setAccessKey = function ( accessKey
) {
3464 accessKey
= typeof accessKey
=== 'string' ? OO
.ui
.resolveMsg( accessKey
) : null;
3466 if ( this.accessKey
!== accessKey
) {
3467 if ( this.$accessKeyed
) {
3468 if ( accessKey
!== null ) {
3469 this.$accessKeyed
.attr( 'accesskey', accessKey
);
3471 this.$accessKeyed
.removeAttr( 'accesskey' );
3474 this.accessKey
= accessKey
;
3483 * @return {string} accessKey string
3485 OO
.ui
.mixin
.AccessKeyedElement
.prototype.getAccessKey = function () {
3486 return this.accessKey
;
3490 * ButtonWidget is a generic widget for buttons. A wide variety of looks,
3491 * feels, and functionality can be customized via the class’s configuration options
3492 * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information
3495 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches
3498 * // A button widget
3499 * var button = new OO.ui.ButtonWidget( {
3500 * label: 'Button with Icon',
3502 * iconTitle: 'Remove'
3504 * $( 'body' ).append( button.$element );
3506 * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class.
3509 * @extends OO.ui.Widget
3510 * @mixins OO.ui.mixin.ButtonElement
3511 * @mixins OO.ui.mixin.IconElement
3512 * @mixins OO.ui.mixin.IndicatorElement
3513 * @mixins OO.ui.mixin.LabelElement
3514 * @mixins OO.ui.mixin.TitledElement
3515 * @mixins OO.ui.mixin.FlaggedElement
3516 * @mixins OO.ui.mixin.TabIndexedElement
3517 * @mixins OO.ui.mixin.AccessKeyedElement
3520 * @param {Object} [config] Configuration options
3521 * @cfg {boolean} [active=false] Whether button should be shown as active
3522 * @cfg {string} [href] Hyperlink to visit when the button is clicked.
3523 * @cfg {string} [target] The frame or window in which to open the hyperlink.
3524 * @cfg {boolean} [noFollow] Search engine traversal hint (default: true)
3526 OO
.ui
.ButtonWidget
= function OoUiButtonWidget( config
) {
3527 // Configuration initialization
3528 config
= config
|| {};
3530 // Parent constructor
3531 OO
.ui
.ButtonWidget
.parent
.call( this, config
);
3533 // Mixin constructors
3534 OO
.ui
.mixin
.ButtonElement
.call( this, config
);
3535 OO
.ui
.mixin
.IconElement
.call( this, config
);
3536 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
3537 OO
.ui
.mixin
.LabelElement
.call( this, config
);
3538 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$button
} ) );
3539 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
3540 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$button
} ) );
3541 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$button
} ) );
3546 this.noFollow
= false;
3549 this.connect( this, { disable
: 'onDisable' } );
3552 this.$button
.append( this.$icon
, this.$label
, this.$indicator
);
3554 .addClass( 'oo-ui-buttonWidget' )
3555 .append( this.$button
);
3556 this.setActive( config
.active
);
3557 this.setHref( config
.href
);
3558 this.setTarget( config
.target
);
3559 this.setNoFollow( config
.noFollow
);
3564 OO
.inheritClass( OO
.ui
.ButtonWidget
, OO
.ui
.Widget
);
3565 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.ButtonElement
);
3566 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IconElement
);
3567 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.IndicatorElement
);
3568 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.LabelElement
);
3569 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TitledElement
);
3570 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.FlaggedElement
);
3571 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.TabIndexedElement
);
3572 OO
.mixinClass( OO
.ui
.ButtonWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
3574 /* Static Properties */
3580 OO
.ui
.ButtonWidget
.static.cancelButtonMouseDownEvents
= false;
3586 OO
.ui
.ButtonWidget
.static.tagName
= 'span';
3591 * Get hyperlink location.
3593 * @return {string} Hyperlink location
3595 OO
.ui
.ButtonWidget
.prototype.getHref = function () {
3600 * Get hyperlink target.
3602 * @return {string} Hyperlink target
3604 OO
.ui
.ButtonWidget
.prototype.getTarget = function () {
3609 * Get search engine traversal hint.
3611 * @return {boolean} Whether search engines should avoid traversing this hyperlink
3613 OO
.ui
.ButtonWidget
.prototype.getNoFollow = function () {
3614 return this.noFollow
;
3618 * Set hyperlink location.
3620 * @param {string|null} href Hyperlink location, null to remove
3622 OO
.ui
.ButtonWidget
.prototype.setHref = function ( href
) {
3623 href
= typeof href
=== 'string' ? href
: null;
3624 if ( href
!== null && !OO
.ui
.isSafeUrl( href
) ) {
3628 if ( href
!== this.href
) {
3637 * Update the `href` attribute, in case of changes to href or
3643 OO
.ui
.ButtonWidget
.prototype.updateHref = function () {
3644 if ( this.href
!== null && !this.isDisabled() ) {
3645 this.$button
.attr( 'href', this.href
);
3647 this.$button
.removeAttr( 'href' );
3654 * Handle disable events.
3657 * @param {boolean} disabled Element is disabled
3659 OO
.ui
.ButtonWidget
.prototype.onDisable = function () {
3664 * Set hyperlink target.
3666 * @param {string|null} target Hyperlink target, null to remove
3668 OO
.ui
.ButtonWidget
.prototype.setTarget = function ( target
) {
3669 target
= typeof target
=== 'string' ? target
: null;
3671 if ( target
!== this.target
) {
3672 this.target
= target
;
3673 if ( target
!== null ) {
3674 this.$button
.attr( 'target', target
);
3676 this.$button
.removeAttr( 'target' );
3684 * Set search engine traversal hint.
3686 * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink
3688 OO
.ui
.ButtonWidget
.prototype.setNoFollow = function ( noFollow
) {
3689 noFollow
= typeof noFollow
=== 'boolean' ? noFollow
: true;
3691 if ( noFollow
!== this.noFollow
) {
3692 this.noFollow
= noFollow
;
3694 this.$button
.attr( 'rel', 'nofollow' );
3696 this.$button
.removeAttr( 'rel' );
3703 // Override method visibility hints from ButtonElement
3714 * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and
3715 * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added,
3716 * removed, and cleared from the group.
3719 * // Example: A ButtonGroupWidget with two buttons
3720 * var button1 = new OO.ui.PopupButtonWidget( {
3721 * label: 'Select a category',
3724 * $content: $( '<p>List of categories...</p>' ),
3729 * var button2 = new OO.ui.ButtonWidget( {
3732 * var buttonGroup = new OO.ui.ButtonGroupWidget( {
3733 * items: [button1, button2]
3735 * $( 'body' ).append( buttonGroup.$element );
3738 * @extends OO.ui.Widget
3739 * @mixins OO.ui.mixin.GroupElement
3742 * @param {Object} [config] Configuration options
3743 * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add
3745 OO
.ui
.ButtonGroupWidget
= function OoUiButtonGroupWidget( config
) {
3746 // Configuration initialization
3747 config
= config
|| {};
3749 // Parent constructor
3750 OO
.ui
.ButtonGroupWidget
.parent
.call( this, config
);
3752 // Mixin constructors
3753 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
3756 this.$element
.addClass( 'oo-ui-buttonGroupWidget' );
3757 if ( Array
.isArray( config
.items
) ) {
3758 this.addItems( config
.items
);
3764 OO
.inheritClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.Widget
);
3765 OO
.mixinClass( OO
.ui
.ButtonGroupWidget
, OO
.ui
.mixin
.GroupElement
);
3767 /* Static Properties */
3773 OO
.ui
.ButtonGroupWidget
.static.tagName
= 'span';
3782 OO
.ui
.ButtonGroupWidget
.prototype.focus = function () {
3783 if ( !this.isDisabled() ) {
3784 if ( this.items
[ 0 ] ) {
3785 this.items
[ 0 ].focus();
3794 OO
.ui
.ButtonGroupWidget
.prototype.simulateLabelClick = function () {
3799 * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
3800 * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
3801 * for a list of icons included in the library.
3804 * // An icon widget with a label
3805 * var myIcon = new OO.ui.IconWidget( {
3809 * // Create a label.
3810 * var iconLabel = new OO.ui.LabelWidget( {
3813 * $( 'body' ).append( myIcon.$element, iconLabel.$element );
3815 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
3818 * @extends OO.ui.Widget
3819 * @mixins OO.ui.mixin.IconElement
3820 * @mixins OO.ui.mixin.TitledElement
3821 * @mixins OO.ui.mixin.FlaggedElement
3824 * @param {Object} [config] Configuration options
3826 OO
.ui
.IconWidget
= function OoUiIconWidget( config
) {
3827 // Configuration initialization
3828 config
= config
|| {};
3830 // Parent constructor
3831 OO
.ui
.IconWidget
.parent
.call( this, config
);
3833 // Mixin constructors
3834 OO
.ui
.mixin
.IconElement
.call( this, $.extend( {}, config
, { $icon
: this.$element
} ) );
3835 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3836 OO
.ui
.mixin
.FlaggedElement
.call( this, $.extend( {}, config
, { $flagged
: this.$element
} ) );
3839 this.$element
.addClass( 'oo-ui-iconWidget' );
3844 OO
.inheritClass( OO
.ui
.IconWidget
, OO
.ui
.Widget
);
3845 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.IconElement
);
3846 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.TitledElement
);
3847 OO
.mixinClass( OO
.ui
.IconWidget
, OO
.ui
.mixin
.FlaggedElement
);
3849 /* Static Properties */
3855 OO
.ui
.IconWidget
.static.tagName
= 'span';
3858 * IndicatorWidgets create indicators, which are small graphics that are generally used to draw
3859 * attention to the status of an item or to clarify the function of a control. For a list of
3860 * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1].
3863 * // Example of an indicator widget
3864 * var indicator1 = new OO.ui.IndicatorWidget( {
3865 * indicator: 'alert'
3868 * // Create a fieldset layout to add a label
3869 * var fieldset = new OO.ui.FieldsetLayout();
3870 * fieldset.addItems( [
3871 * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } )
3873 * $( 'body' ).append( fieldset.$element );
3875 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators
3878 * @extends OO.ui.Widget
3879 * @mixins OO.ui.mixin.IndicatorElement
3880 * @mixins OO.ui.mixin.TitledElement
3883 * @param {Object} [config] Configuration options
3885 OO
.ui
.IndicatorWidget
= function OoUiIndicatorWidget( config
) {
3886 // Configuration initialization
3887 config
= config
|| {};
3889 // Parent constructor
3890 OO
.ui
.IndicatorWidget
.parent
.call( this, config
);
3892 // Mixin constructors
3893 OO
.ui
.mixin
.IndicatorElement
.call( this, $.extend( {}, config
, { $indicator
: this.$element
} ) );
3894 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$element
} ) );
3897 this.$element
.addClass( 'oo-ui-indicatorWidget' );
3902 OO
.inheritClass( OO
.ui
.IndicatorWidget
, OO
.ui
.Widget
);
3903 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.IndicatorElement
);
3904 OO
.mixinClass( OO
.ui
.IndicatorWidget
, OO
.ui
.mixin
.TitledElement
);
3906 /* Static Properties */
3912 OO
.ui
.IndicatorWidget
.static.tagName
= 'span';
3915 * LabelWidgets help identify the function of interface elements. Each LabelWidget can
3916 * be configured with a `label` option that is set to a string, a label node, or a function:
3918 * - String: a plaintext string
3919 * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a
3920 * label that includes a link or special styling, such as a gray color or additional graphical elements.
3921 * - Function: a function that will produce a string in the future. Functions are used
3922 * in cases where the value of the label is not currently defined.
3924 * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which
3925 * will come into focus when the label is clicked.
3928 * // Examples of LabelWidgets
3929 * var label1 = new OO.ui.LabelWidget( {
3930 * label: 'plaintext label'
3932 * var label2 = new OO.ui.LabelWidget( {
3933 * label: $( '<a href="default.html">jQuery label</a>' )
3935 * // Create a fieldset layout with fields for each example
3936 * var fieldset = new OO.ui.FieldsetLayout();
3937 * fieldset.addItems( [
3938 * new OO.ui.FieldLayout( label1 ),
3939 * new OO.ui.FieldLayout( label2 )
3941 * $( 'body' ).append( fieldset.$element );
3944 * @extends OO.ui.Widget
3945 * @mixins OO.ui.mixin.LabelElement
3946 * @mixins OO.ui.mixin.TitledElement
3949 * @param {Object} [config] Configuration options
3950 * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label.
3951 * Clicking the label will focus the specified input field.
3953 OO
.ui
.LabelWidget
= function OoUiLabelWidget( config
) {
3954 // Configuration initialization
3955 config
= config
|| {};
3957 // Parent constructor
3958 OO
.ui
.LabelWidget
.parent
.call( this, config
);
3960 // Mixin constructors
3961 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: this.$element
} ) );
3962 OO
.ui
.mixin
.TitledElement
.call( this, config
);
3965 this.input
= config
.input
;
3969 if ( this.input
.getInputId() ) {
3970 this.$element
.attr( 'for', this.input
.getInputId() );
3972 this.$label
.on( 'click', function () {
3973 this.input
.simulateLabelClick();
3978 this.$element
.addClass( 'oo-ui-labelWidget' );
3983 OO
.inheritClass( OO
.ui
.LabelWidget
, OO
.ui
.Widget
);
3984 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.LabelElement
);
3985 OO
.mixinClass( OO
.ui
.LabelWidget
, OO
.ui
.mixin
.TitledElement
);
3987 /* Static Properties */
3993 OO
.ui
.LabelWidget
.static.tagName
= 'label';
3996 * PendingElement is a mixin that is used to create elements that notify users that something is happening
3997 * and that they should wait before proceeding. The pending state is visually represented with a pending
3998 * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input
3999 * field of a {@link OO.ui.TextInputWidget text input widget}.
4001 * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when
4002 * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used
4003 * in process dialogs.
4006 * function MessageDialog( config ) {
4007 * MessageDialog.parent.call( this, config );
4009 * OO.inheritClass( MessageDialog, OO.ui.MessageDialog );
4011 * MessageDialog.static.name = 'myMessageDialog';
4012 * MessageDialog.static.actions = [
4013 * { action: 'save', label: 'Done', flags: 'primary' },
4014 * { label: 'Cancel', flags: 'safe' }
4017 * MessageDialog.prototype.initialize = function () {
4018 * MessageDialog.parent.prototype.initialize.apply( this, arguments );
4019 * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } );
4020 * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' );
4021 * this.$body.append( this.content.$element );
4023 * MessageDialog.prototype.getBodyHeight = function () {
4026 * MessageDialog.prototype.getActionProcess = function ( action ) {
4027 * var dialog = this;
4028 * if ( action === 'save' ) {
4029 * dialog.getActions().get({actions: 'save'})[0].pushPending();
4030 * return new OO.ui.Process()
4032 * .next( function () {
4033 * dialog.getActions().get({actions: 'save'})[0].popPending();
4036 * return MessageDialog.parent.prototype.getActionProcess.call( this, action );
4039 * var windowManager = new OO.ui.WindowManager();
4040 * $( 'body' ).append( windowManager.$element );
4042 * var dialog = new MessageDialog();
4043 * windowManager.addWindows( [ dialog ] );
4044 * windowManager.openWindow( dialog );
4050 * @param {Object} [config] Configuration options
4051 * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element
4053 OO
.ui
.mixin
.PendingElement
= function OoUiMixinPendingElement( config
) {
4054 // Configuration initialization
4055 config
= config
|| {};
4059 this.$pending
= null;
4062 this.setPendingElement( config
.$pending
|| this.$element
);
4067 OO
.initClass( OO
.ui
.mixin
.PendingElement
);
4072 * Set the pending element (and clean up any existing one).
4074 * @param {jQuery} $pending The element to set to pending.
4076 OO
.ui
.mixin
.PendingElement
.prototype.setPendingElement = function ( $pending
) {
4077 if ( this.$pending
) {
4078 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4081 this.$pending
= $pending
;
4082 if ( this.pending
> 0 ) {
4083 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4088 * Check if an element is pending.
4090 * @return {boolean} Element is pending
4092 OO
.ui
.mixin
.PendingElement
.prototype.isPending = function () {
4093 return !!this.pending
;
4097 * Increase the pending counter. The pending state will remain active until the counter is zero
4098 * (i.e., the number of calls to #pushPending and #popPending is the same).
4102 OO
.ui
.mixin
.PendingElement
.prototype.pushPending = function () {
4103 if ( this.pending
=== 0 ) {
4104 this.$pending
.addClass( 'oo-ui-pendingElement-pending' );
4105 this.updateThemeClasses();
4113 * Decrease the pending counter. The pending state will remain active until the counter is zero
4114 * (i.e., the number of calls to #pushPending and #popPending is the same).
4118 OO
.ui
.mixin
.PendingElement
.prototype.popPending = function () {
4119 if ( this.pending
=== 1 ) {
4120 this.$pending
.removeClass( 'oo-ui-pendingElement-pending' );
4121 this.updateThemeClasses();
4123 this.pending
= Math
.max( 0, this.pending
- 1 );
4129 * Element that will stick adjacent to a specified container, even when it is inserted elsewhere
4130 * in the document (for example, in an OO.ui.Window's $overlay).
4132 * The elements's position is automatically calculated and maintained when window is resized or the
4133 * page is scrolled. If you reposition the container manually, you have to call #position to make
4134 * sure the element is still placed correctly.
4136 * As positioning is only possible when both the element and the container are attached to the DOM
4137 * and visible, it's only done after you call #togglePositioning. You might want to do this inside
4138 * the #toggle method to display a floating popup, for example.
4144 * @param {Object} [config] Configuration options
4145 * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element
4146 * @cfg {jQuery} [$floatableContainer] Node to position adjacent to
4147 * @cfg {string} [verticalPosition='below'] Where to position $floatable vertically:
4148 * 'below': Directly below $floatableContainer, aligning f's top edge with fC's bottom edge
4149 * 'above': Directly above $floatableContainer, aligning f's bottom edge with fC's top edge
4150 * 'top': Align the top edge with $floatableContainer's top edge
4151 * 'bottom': Align the bottom edge with $floatableContainer's bottom edge
4152 * 'center': Vertically align the center with $floatableContainer's center
4153 * @cfg {string} [horizontalPosition='start'] Where to position $floatable horizontally:
4154 * 'before': Directly before $floatableContainer, aligning f's end edge with fC's start edge
4155 * 'after': Directly after $floatableContainer, algining f's start edge with fC's end edge
4156 * 'start': Align the start (left in LTR, right in RTL) edge with $floatableContainer's start edge
4157 * 'end': Align the end (right in LTR, left in RTL) edge with $floatableContainer's end edge
4158 * 'center': Horizontally align the center with $floatableContainer's center
4159 * @cfg {boolean} [hideWhenOutOfView=true] Whether to hide the floatable element if the container
4162 OO
.ui
.mixin
.FloatableElement
= function OoUiMixinFloatableElement( config
) {
4163 // Configuration initialization
4164 config
= config
|| {};
4167 this.$floatable
= null;
4168 this.$floatableContainer
= null;
4169 this.$floatableWindow
= null;
4170 this.$floatableClosestScrollable
= null;
4171 this.onFloatableScrollHandler
= this.position
.bind( this );
4172 this.onFloatableWindowResizeHandler
= this.position
.bind( this );
4175 this.setFloatableContainer( config
.$floatableContainer
);
4176 this.setFloatableElement( config
.$floatable
|| this.$element
);
4177 this.setVerticalPosition( config
.verticalPosition
|| 'below' );
4178 this.setHorizontalPosition( config
.horizontalPosition
|| 'start' );
4179 this.hideWhenOutOfView
= config
.hideWhenOutOfView
=== undefined ? true : !!config
.hideWhenOutOfView
;
4185 * Set floatable element.
4187 * If an element is already set, it will be cleaned up before setting up the new element.
4189 * @param {jQuery} $floatable Element to make floatable
4191 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableElement = function ( $floatable
) {
4192 if ( this.$floatable
) {
4193 this.$floatable
.removeClass( 'oo-ui-floatableElement-floatable' );
4194 this.$floatable
.css( { left
: '', top
: '' } );
4197 this.$floatable
= $floatable
.addClass( 'oo-ui-floatableElement-floatable' );
4202 * Set floatable container.
4204 * The element will be positioned relative to the specified container.
4206 * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset
4208 OO
.ui
.mixin
.FloatableElement
.prototype.setFloatableContainer = function ( $floatableContainer
) {
4209 this.$floatableContainer
= $floatableContainer
;
4210 if ( this.$floatable
) {
4216 * Change how the element is positioned vertically.
4218 * @param {string} position 'below', 'above', 'top', 'bottom' or 'center'
4220 OO
.ui
.mixin
.FloatableElement
.prototype.setVerticalPosition = function ( position
) {
4221 if ( [ 'below', 'above', 'top', 'bottom', 'center' ].indexOf( position
) === -1 ) {
4222 throw new Error( 'Invalid value for vertical position: ' + position
);
4224 if ( this.verticalPosition
!== position
) {
4225 this.verticalPosition
= position
;
4226 if ( this.$floatable
) {
4233 * Change how the element is positioned horizontally.
4235 * @param {string} position 'before', 'after', 'start', 'end' or 'center'
4237 OO
.ui
.mixin
.FloatableElement
.prototype.setHorizontalPosition = function ( position
) {
4238 if ( [ 'before', 'after', 'start', 'end', 'center' ].indexOf( position
) === -1 ) {
4239 throw new Error( 'Invalid value for horizontal position: ' + position
);
4241 if ( this.horizontalPosition
!== position
) {
4242 this.horizontalPosition
= position
;
4243 if ( this.$floatable
) {
4250 * Toggle positioning.
4252 * Do not turn positioning on until after the element is attached to the DOM and visible.
4254 * @param {boolean} [positioning] Enable positioning, omit to toggle
4257 OO
.ui
.mixin
.FloatableElement
.prototype.togglePositioning = function ( positioning
) {
4258 var closestScrollableOfContainer
;
4260 if ( !this.$floatable
|| !this.$floatableContainer
) {
4264 positioning
= positioning
=== undefined ? !this.positioning
: !!positioning
;
4266 if ( positioning
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4267 OO
.ui
.warnDeprecation( 'FloatableElement#togglePositioning: Before calling this method, the element must be attached to the DOM.' );
4268 this.warnedUnattached
= true;
4271 if ( this.positioning
!== positioning
) {
4272 this.positioning
= positioning
;
4274 this.needsCustomPosition
=
4275 this.verticalPostion
!== 'below' ||
4276 this.horizontalPosition
!== 'start' ||
4277 !OO
.ui
.contains( this.$floatableContainer
[ 0 ], this.$floatable
[ 0 ] );
4279 closestScrollableOfContainer
= OO
.ui
.Element
.static.getClosestScrollableContainer( this.$floatableContainer
[ 0 ] );
4280 // If the scrollable is the root, we have to listen to scroll events
4281 // on the window because of browser inconsistencies.
4282 if ( $( closestScrollableOfContainer
).is( 'html, body' ) ) {
4283 closestScrollableOfContainer
= OO
.ui
.Element
.static.getWindow( closestScrollableOfContainer
);
4286 if ( positioning
) {
4287 this.$floatableWindow
= $( this.getElementWindow() );
4288 this.$floatableWindow
.on( 'resize', this.onFloatableWindowResizeHandler
);
4290 this.$floatableClosestScrollable
= $( closestScrollableOfContainer
);
4291 this.$floatableClosestScrollable
.on( 'scroll', this.onFloatableScrollHandler
);
4293 // Initial position after visible
4296 if ( this.$floatableWindow
) {
4297 this.$floatableWindow
.off( 'resize', this.onFloatableWindowResizeHandler
);
4298 this.$floatableWindow
= null;
4301 if ( this.$floatableClosestScrollable
) {
4302 this.$floatableClosestScrollable
.off( 'scroll', this.onFloatableScrollHandler
);
4303 this.$floatableClosestScrollable
= null;
4306 this.$floatable
.css( { left
: '', right
: '', top
: '' } );
4314 * Check whether the bottom edge of the given element is within the viewport of the given container.
4317 * @param {jQuery} $element
4318 * @param {jQuery} $container
4321 OO
.ui
.mixin
.FloatableElement
.prototype.isElementInViewport = function ( $element
, $container
) {
4322 var elemRect
, contRect
, topEdgeInBounds
, bottomEdgeInBounds
, leftEdgeInBounds
, rightEdgeInBounds
,
4323 startEdgeInBounds
, endEdgeInBounds
,
4324 direction
= $element
.css( 'direction' );
4326 elemRect
= $element
[ 0 ].getBoundingClientRect();
4327 if ( $container
[ 0 ] === window
) {
4331 right
: document
.documentElement
.clientWidth
,
4332 bottom
: document
.documentElement
.clientHeight
4335 contRect
= $container
[ 0 ].getBoundingClientRect();
4338 topEdgeInBounds
= elemRect
.top
>= contRect
.top
&& elemRect
.top
<= contRect
.bottom
;
4339 bottomEdgeInBounds
= elemRect
.bottom
>= contRect
.top
&& elemRect
.bottom
<= contRect
.bottom
;
4340 leftEdgeInBounds
= elemRect
.left
>= contRect
.left
&& elemRect
.left
<= contRect
.right
;
4341 rightEdgeInBounds
= elemRect
.right
>= contRect
.left
&& elemRect
.right
<= contRect
.right
;
4342 if ( direction
=== 'rtl' ) {
4343 startEdgeInBounds
= rightEdgeInBounds
;
4344 endEdgeInBounds
= leftEdgeInBounds
;
4346 startEdgeInBounds
= leftEdgeInBounds
;
4347 endEdgeInBounds
= rightEdgeInBounds
;
4350 if ( this.verticalPosition
=== 'below' && !bottomEdgeInBounds
) {
4353 if ( this.verticalPosition
=== 'above' && !topEdgeInBounds
) {
4356 if ( this.horizontalPosition
=== 'before' && !startEdgeInBounds
) {
4359 if ( this.horizontalPosition
=== 'after' && !endEdgeInBounds
) {
4363 // The other positioning values are all about being inside the container,
4364 // so in those cases all we care about is that any part of the container is visible.
4365 return elemRect
.top
<= contRect
.bottom
&& elemRect
.bottom
>= contRect
.top
&&
4366 elemRect
.left
<= contRect
.right
&& elemRect
.right
>= contRect
.left
;
4370 * Position the floatable below its container.
4372 * This should only be done when both of them are attached to the DOM and visible.
4376 OO
.ui
.mixin
.FloatableElement
.prototype.position = function () {
4377 if ( !this.positioning
) {
4382 // To continue, some things need to be true:
4383 // The element must actually be in the DOM
4384 this.isElementAttached() && (
4385 // The closest scrollable is the current window
4386 this.$floatableClosestScrollable
[ 0 ] === this.getElementWindow() ||
4387 // OR is an element in the element's DOM
4388 $.contains( this.getElementDocument(), this.$floatableClosestScrollable
[ 0 ] )
4391 // Abort early if important parts of the widget are no longer attached to the DOM
4395 if ( this.hideWhenOutOfView
&& !this.isElementInViewport( this.$floatableContainer
, this.$floatableClosestScrollable
) ) {
4396 this.$floatable
.addClass( 'oo-ui-element-hidden' );
4399 this.$floatable
.removeClass( 'oo-ui-element-hidden' );
4402 if ( !this.needsCustomPosition
) {
4406 this.$floatable
.css( this.computePosition() );
4408 // We updated the position, so re-evaluate the clipping state.
4409 // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so
4410 // will not notice the need to update itself.)
4411 // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does
4412 // it not listen to the right events in the right places?
4421 * Compute how #$floatable should be positioned based on the position of #$floatableContainer
4422 * and the positioning settings. This is a helper for #position that shouldn't be called directly,
4423 * but may be overridden by subclasses if they want to change or add to the positioning logic.
4425 * @return {Object} New position to apply with .css(). Keys are 'top', 'left', 'bottom' and 'right'.
4427 OO
.ui
.mixin
.FloatableElement
.prototype.computePosition = function () {
4428 var isBody
, scrollableX
, scrollableY
, containerPos
,
4429 horizScrollbarHeight
, vertScrollbarWidth
, scrollTop
, scrollLeft
,
4430 newPos
= { top
: '', left
: '', bottom
: '', right
: '' },
4431 direction
= this.$floatableContainer
.css( 'direction' ),
4432 $offsetParent
= this.$floatable
.offsetParent();
4434 if ( $offsetParent
.is( 'html' ) ) {
4435 // The innerHeight/Width and clientHeight/Width calculations don't work well on the
4436 // <html> element, but they do work on the <body>
4437 $offsetParent
= $( $offsetParent
[ 0 ].ownerDocument
.body
);
4439 isBody
= $offsetParent
.is( 'body' );
4440 scrollableX
= $offsetParent
.css( 'overflow-x' ) === 'scroll' || $offsetParent
.css( 'overflow-x' ) === 'auto';
4441 scrollableY
= $offsetParent
.css( 'overflow-y' ) === 'scroll' || $offsetParent
.css( 'overflow-y' ) === 'auto';
4443 vertScrollbarWidth
= $offsetParent
.innerWidth() - $offsetParent
.prop( 'clientWidth' );
4444 horizScrollbarHeight
= $offsetParent
.innerHeight() - $offsetParent
.prop( 'clientHeight' );
4445 // We don't need to compute and add scrollTop and scrollLeft if the scrollable container is the body,
4446 // or if it isn't scrollable
4447 scrollTop
= scrollableY
&& !isBody
? $offsetParent
.scrollTop() : 0;
4448 scrollLeft
= scrollableX
&& !isBody
? OO
.ui
.Element
.static.getScrollLeft( $offsetParent
[ 0 ] ) : 0;
4450 // Avoid passing the <body> to getRelativePosition(), because it won't return what we expect
4451 // if the <body> has a margin
4452 containerPos
= isBody
?
4453 this.$floatableContainer
.offset() :
4454 OO
.ui
.Element
.static.getRelativePosition( this.$floatableContainer
, $offsetParent
);
4455 containerPos
.bottom
= containerPos
.top
+ this.$floatableContainer
.outerHeight();
4456 containerPos
.right
= containerPos
.left
+ this.$floatableContainer
.outerWidth();
4457 containerPos
.start
= direction
=== 'rtl' ? containerPos
.right
: containerPos
.left
;
4458 containerPos
.end
= direction
=== 'rtl' ? containerPos
.left
: containerPos
.right
;
4460 if ( this.verticalPosition
=== 'below' ) {
4461 newPos
.top
= containerPos
.bottom
;
4462 } else if ( this.verticalPosition
=== 'above' ) {
4463 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.top
;
4464 } else if ( this.verticalPosition
=== 'top' ) {
4465 newPos
.top
= containerPos
.top
;
4466 } else if ( this.verticalPosition
=== 'bottom' ) {
4467 newPos
.bottom
= $offsetParent
.outerHeight() - containerPos
.bottom
;
4468 } else if ( this.verticalPosition
=== 'center' ) {
4469 newPos
.top
= containerPos
.top
+
4470 ( this.$floatableContainer
.height() - this.$floatable
.height() ) / 2;
4473 if ( this.horizontalPosition
=== 'before' ) {
4474 newPos
.end
= containerPos
.start
;
4475 } else if ( this.horizontalPosition
=== 'after' ) {
4476 newPos
.start
= containerPos
.end
;
4477 } else if ( this.horizontalPosition
=== 'start' ) {
4478 newPos
.start
= containerPos
.start
;
4479 } else if ( this.horizontalPosition
=== 'end' ) {
4480 newPos
.end
= containerPos
.end
;
4481 } else if ( this.horizontalPosition
=== 'center' ) {
4482 newPos
.left
= containerPos
.left
+
4483 ( this.$floatableContainer
.width() - this.$floatable
.width() ) / 2;
4486 if ( newPos
.start
!== undefined ) {
4487 if ( direction
=== 'rtl' ) {
4488 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.start
;
4490 newPos
.left
= newPos
.start
;
4492 delete newPos
.start
;
4494 if ( newPos
.end
!== undefined ) {
4495 if ( direction
=== 'rtl' ) {
4496 newPos
.left
= newPos
.end
;
4498 newPos
.right
= ( isBody
? $( $offsetParent
[ 0 ].ownerDocument
.documentElement
) : $offsetParent
).outerWidth() - newPos
.end
;
4503 // Account for scroll position
4504 if ( newPos
.top
!== '' ) {
4505 newPos
.top
+= scrollTop
;
4507 if ( newPos
.bottom
!== '' ) {
4508 newPos
.bottom
-= scrollTop
;
4510 if ( newPos
.left
!== '' ) {
4511 newPos
.left
+= scrollLeft
;
4513 if ( newPos
.right
!== '' ) {
4514 newPos
.right
-= scrollLeft
;
4517 // Account for scrollbar gutter
4518 if ( newPos
.bottom
!== '' ) {
4519 newPos
.bottom
-= horizScrollbarHeight
;
4521 if ( direction
=== 'rtl' ) {
4522 if ( newPos
.left
!== '' ) {
4523 newPos
.left
-= vertScrollbarWidth
;
4526 if ( newPos
.right
!== '' ) {
4527 newPos
.right
-= vertScrollbarWidth
;
4535 * Element that can be automatically clipped to visible boundaries.
4537 * Whenever the element's natural height changes, you have to call
4538 * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still
4539 * clipping correctly.
4541 * The dimensions of #$clippableContainer will be compared to the boundaries of the
4542 * nearest scrollable container. If #$clippableContainer is too tall and/or too wide,
4543 * then #$clippable will be given a fixed reduced height and/or width and will be made
4544 * scrollable. By default, #$clippable and #$clippableContainer are the same element,
4545 * but you can build a static footer by setting #$clippableContainer to an element that contains
4546 * #$clippable and the footer.
4552 * @param {Object} [config] Configuration options
4553 * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element
4554 * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer,
4555 * omit to use #$clippable
4557 OO
.ui
.mixin
.ClippableElement
= function OoUiMixinClippableElement( config
) {
4558 // Configuration initialization
4559 config
= config
|| {};
4562 this.$clippable
= null;
4563 this.$clippableContainer
= null;
4564 this.clipping
= false;
4565 this.clippedHorizontally
= false;
4566 this.clippedVertically
= false;
4567 this.$clippableScrollableContainer
= null;
4568 this.$clippableScroller
= null;
4569 this.$clippableWindow
= null;
4570 this.idealWidth
= null;
4571 this.idealHeight
= null;
4572 this.onClippableScrollHandler
= this.clip
.bind( this );
4573 this.onClippableWindowResizeHandler
= this.clip
.bind( this );
4576 if ( config
.$clippableContainer
) {
4577 this.setClippableContainer( config
.$clippableContainer
);
4579 this.setClippableElement( config
.$clippable
|| this.$element
);
4585 * Set clippable element.
4587 * If an element is already set, it will be cleaned up before setting up the new element.
4589 * @param {jQuery} $clippable Element to make clippable
4591 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableElement = function ( $clippable
) {
4592 if ( this.$clippable
) {
4593 this.$clippable
.removeClass( 'oo-ui-clippableElement-clippable' );
4594 this.$clippable
.css( { width
: '', height
: '', overflowX
: '', overflowY
: '' } );
4595 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4598 this.$clippable
= $clippable
.addClass( 'oo-ui-clippableElement-clippable' );
4603 * Set clippable container.
4605 * This is the container that will be measured when deciding whether to clip. When clipping,
4606 * #$clippable will be resized in order to keep the clippable container fully visible.
4608 * If the clippable container is unset, #$clippable will be used.
4610 * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset
4612 OO
.ui
.mixin
.ClippableElement
.prototype.setClippableContainer = function ( $clippableContainer
) {
4613 this.$clippableContainer
= $clippableContainer
;
4614 if ( this.$clippable
) {
4622 * Do not turn clipping on until after the element is attached to the DOM and visible.
4624 * @param {boolean} [clipping] Enable clipping, omit to toggle
4627 OO
.ui
.mixin
.ClippableElement
.prototype.toggleClipping = function ( clipping
) {
4628 clipping
= clipping
=== undefined ? !this.clipping
: !!clipping
;
4630 if ( clipping
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
4631 OO
.ui
.warnDeprecation( 'ClippableElement#toggleClipping: Before calling this method, the element must be attached to the DOM.' );
4632 this.warnedUnattached
= true;
4635 if ( this.clipping
!== clipping
) {
4636 this.clipping
= clipping
;
4638 this.$clippableScrollableContainer
= $( this.getClosestScrollableElementContainer() );
4639 // If the clippable container is the root, we have to listen to scroll events and check
4640 // jQuery.scrollTop on the window because of browser inconsistencies
4641 this.$clippableScroller
= this.$clippableScrollableContainer
.is( 'html, body' ) ?
4642 $( OO
.ui
.Element
.static.getWindow( this.$clippableScrollableContainer
) ) :
4643 this.$clippableScrollableContainer
;
4644 this.$clippableScroller
.on( 'scroll', this.onClippableScrollHandler
);
4645 this.$clippableWindow
= $( this.getElementWindow() )
4646 .on( 'resize', this.onClippableWindowResizeHandler
);
4647 // Initial clip after visible
4650 this.$clippable
.css( {
4658 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4660 this.$clippableScrollableContainer
= null;
4661 this.$clippableScroller
.off( 'scroll', this.onClippableScrollHandler
);
4662 this.$clippableScroller
= null;
4663 this.$clippableWindow
.off( 'resize', this.onClippableWindowResizeHandler
);
4664 this.$clippableWindow
= null;
4672 * Check if the element will be clipped to fit the visible area of the nearest scrollable container.
4674 * @return {boolean} Element will be clipped to the visible area
4676 OO
.ui
.mixin
.ClippableElement
.prototype.isClipping = function () {
4677 return this.clipping
;
4681 * Check if the bottom or right of the element is being clipped by the nearest scrollable container.
4683 * @return {boolean} Part of the element is being clipped
4685 OO
.ui
.mixin
.ClippableElement
.prototype.isClipped = function () {
4686 return this.clippedHorizontally
|| this.clippedVertically
;
4690 * Check if the right of the element is being clipped by the nearest scrollable container.
4692 * @return {boolean} Part of the element is being clipped
4694 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedHorizontally = function () {
4695 return this.clippedHorizontally
;
4699 * Check if the bottom of the element is being clipped by the nearest scrollable container.
4701 * @return {boolean} Part of the element is being clipped
4703 OO
.ui
.mixin
.ClippableElement
.prototype.isClippedVertically = function () {
4704 return this.clippedVertically
;
4708 * Set the ideal size. These are the dimensions #$clippable will have when it's not being clipped.
4710 * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix
4711 * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix
4713 OO
.ui
.mixin
.ClippableElement
.prototype.setIdealSize = function ( width
, height
) {
4714 this.idealWidth
= width
;
4715 this.idealHeight
= height
;
4717 if ( !this.clipping
) {
4718 // Update dimensions
4719 this.$clippable
.css( { width
: width
, height
: height
} );
4721 // While clipping, idealWidth and idealHeight are not considered
4725 * Clip element to visible boundaries and allow scrolling when needed. You should call this method
4726 * when the element's natural height changes.
4728 * Element will be clipped the bottom or right of the element is within 10px of the edge of, or
4729 * overlapped by, the visible area of the nearest scrollable container.
4731 * Because calling clip() when the natural height changes isn't always possible, we also set
4732 * max-height when the element isn't being clipped. This means that if the element tries to grow
4733 * beyond the edge, something reasonable will happen before clip() is called.
4737 OO
.ui
.mixin
.ClippableElement
.prototype.clip = function () {
4738 var $container
, extraHeight
, extraWidth
, ccOffset
,
4739 $scrollableContainer
, scOffset
, scHeight
, scWidth
,
4740 ccWidth
, scrollerIsWindow
, scrollTop
, scrollLeft
,
4741 desiredWidth
, desiredHeight
, allotedWidth
, allotedHeight
,
4742 naturalWidth
, naturalHeight
, clipWidth
, clipHeight
,
4743 buffer
= 7; // Chosen by fair dice roll
4745 if ( !this.clipping
) {
4746 // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail
4750 $container
= this.$clippableContainer
|| this.$clippable
;
4751 extraHeight
= $container
.outerHeight() - this.$clippable
.outerHeight();
4752 extraWidth
= $container
.outerWidth() - this.$clippable
.outerWidth();
4753 ccOffset
= $container
.offset();
4754 if ( this.$clippableScrollableContainer
.is( 'html, body' ) ) {
4755 $scrollableContainer
= this.$clippableWindow
;
4756 scOffset
= { top
: 0, left
: 0 };
4758 $scrollableContainer
= this.$clippableScrollableContainer
;
4759 scOffset
= $scrollableContainer
.offset();
4761 scHeight
= $scrollableContainer
.innerHeight() - buffer
;
4762 scWidth
= $scrollableContainer
.innerWidth() - buffer
;
4763 ccWidth
= $container
.outerWidth() + buffer
;
4764 scrollerIsWindow
= this.$clippableScroller
[ 0 ] === this.$clippableWindow
[ 0 ];
4765 scrollTop
= scrollerIsWindow
? this.$clippableScroller
.scrollTop() : 0;
4766 scrollLeft
= scrollerIsWindow
? this.$clippableScroller
.scrollLeft() : 0;
4767 desiredWidth
= ccOffset
.left
< 0 ?
4768 ccWidth
+ ccOffset
.left
:
4769 ( scOffset
.left
+ scrollLeft
+ scWidth
) - ccOffset
.left
;
4770 desiredHeight
= ( scOffset
.top
+ scrollTop
+ scHeight
) - ccOffset
.top
;
4771 // It should never be desirable to exceed the dimensions of the browser viewport... right?
4772 desiredWidth
= Math
.min( desiredWidth
, document
.documentElement
.clientWidth
);
4773 desiredHeight
= Math
.min( desiredHeight
, document
.documentElement
.clientHeight
);
4774 allotedWidth
= Math
.ceil( desiredWidth
- extraWidth
);
4775 allotedHeight
= Math
.ceil( desiredHeight
- extraHeight
);
4776 naturalWidth
= this.$clippable
.prop( 'scrollWidth' );
4777 naturalHeight
= this.$clippable
.prop( 'scrollHeight' );
4778 clipWidth
= allotedWidth
< naturalWidth
;
4779 clipHeight
= allotedHeight
< naturalHeight
;
4782 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4783 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4784 this.$clippable
.css( 'overflowX', 'scroll' );
4785 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4786 this.$clippable
.css( {
4787 width
: Math
.max( 0, allotedWidth
),
4791 this.$clippable
.css( {
4793 width
: this.idealWidth
|| '',
4794 maxWidth
: Math
.max( 0, allotedWidth
)
4798 // The order matters here. If overflow is not set first, Chrome displays bogus scrollbars. (T157672)
4799 // Forcing a reflow is a smaller workaround than calling reconsiderScrollbars() for this case.
4800 this.$clippable
.css( 'overflowY', 'scroll' );
4801 void this.$clippable
[ 0 ].offsetHeight
; // Force reflow
4802 this.$clippable
.css( {
4803 height
: Math
.max( 0, allotedHeight
),
4807 this.$clippable
.css( {
4809 height
: this.idealHeight
|| '',
4810 maxHeight
: Math
.max( 0, allotedHeight
)
4814 // If we stopped clipping in at least one of the dimensions
4815 if ( ( this.clippedHorizontally
&& !clipWidth
) || ( this.clippedVertically
&& !clipHeight
) ) {
4816 OO
.ui
.Element
.static.reconsiderScrollbars( this.$clippable
[ 0 ] );
4819 this.clippedHorizontally
= clipWidth
;
4820 this.clippedVertically
= clipHeight
;
4826 * PopupWidget is a container for content. The popup is overlaid and positioned absolutely.
4827 * By default, each popup has an anchor that points toward its origin.
4828 * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples.
4830 * Unlike most widgets, PopupWidget is initially hidden and must be shown by calling #toggle.
4833 * // A popup widget.
4834 * var popup = new OO.ui.PopupWidget( {
4835 * $content: $( '<p>Hi there!</p>' ),
4840 * $( 'body' ).append( popup.$element );
4841 * // To display the popup, toggle the visibility to 'true'.
4842 * popup.toggle( true );
4844 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups
4847 * @extends OO.ui.Widget
4848 * @mixins OO.ui.mixin.LabelElement
4849 * @mixins OO.ui.mixin.ClippableElement
4850 * @mixins OO.ui.mixin.FloatableElement
4853 * @param {Object} [config] Configuration options
4854 * @cfg {number} [width=320] Width of popup in pixels
4855 * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height.
4856 * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup
4857 * @cfg {string} [position='below'] Where to position the popup relative to $floatableContainer
4858 * 'above': Put popup above $floatableContainer; anchor points down to the horizontal center
4859 * of $floatableContainer
4860 * 'below': Put popup below $floatableContainer; anchor points up to the horizontal center
4861 * of $floatableContainer
4862 * 'before': Put popup to the left (LTR) / right (RTL) of $floatableContainer; anchor points
4863 * endwards (right/left) to the vertical center of $floatableContainer
4864 * 'after': Put popup to the right (LTR) / left (RTL) of $floatableContainer; anchor points
4865 * startwards (left/right) to the vertical center of $floatableContainer
4866 * @cfg {string} [align='center'] How to align the popup to $floatableContainer
4867 * 'forwards': If position is above/below, move the popup as far endwards (right in LTR, left in RTL)
4868 * as possible while still keeping the anchor within the popup;
4869 * if position is before/after, move the popup as far downwards as possible.
4870 * 'backwards': If position is above/below, move the popup as far startwards (left in LTR, right in RTL)
4871 * as possible while still keeping the anchor within the popup;
4872 * if position in before/after, move the popup as far upwards as possible.
4873 * 'center': Horizontally (if position is above/below) or vertically (before/after) align the center
4874 * of the popup with the center of $floatableContainer.
4875 * 'force-left': Alias for 'forwards' in LTR and 'backwards' in RTL
4876 * 'force-right': Alias for 'backwards' in RTL and 'forwards' in LTR
4877 * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container.
4878 * See the [OOjs UI docs on MediaWiki][3] for an example.
4879 * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample
4880 * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels.
4881 * @cfg {jQuery} [$content] Content to append to the popup's body
4882 * @cfg {jQuery} [$footer] Content to append to the popup's footer
4883 * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus.
4884 * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked.
4885 * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2]
4887 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample
4888 * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close
4890 * @cfg {boolean} [padded=false] Add padding to the popup's body
4892 OO
.ui
.PopupWidget
= function OoUiPopupWidget( config
) {
4893 // Configuration initialization
4894 config
= config
|| {};
4896 // Parent constructor
4897 OO
.ui
.PopupWidget
.parent
.call( this, config
);
4899 // Properties (must be set before ClippableElement constructor call)
4900 this.$body
= $( '<div>' );
4901 this.$popup
= $( '<div>' );
4903 // Mixin constructors
4904 OO
.ui
.mixin
.LabelElement
.call( this, config
);
4905 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, {
4906 $clippable
: this.$body
,
4907 $clippableContainer
: this.$popup
4909 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
4912 this.$anchor
= $( '<div>' );
4913 // If undefined, will be computed lazily in updateDimensions()
4914 this.$container
= config
.$container
;
4915 this.containerPadding
= config
.containerPadding
!== undefined ? config
.containerPadding
: 10;
4916 this.autoClose
= !!config
.autoClose
;
4917 this.$autoCloseIgnore
= config
.$autoCloseIgnore
;
4918 this.transitionTimeout
= null;
4919 this.anchored
= false;
4920 this.width
= config
.width
!== undefined ? config
.width
: 320;
4921 this.height
= config
.height
!== undefined ? config
.height
: null;
4922 this.onMouseDownHandler
= this.onMouseDown
.bind( this );
4923 this.onDocumentKeyDownHandler
= this.onDocumentKeyDown
.bind( this );
4926 this.toggleAnchor( config
.anchor
=== undefined || config
.anchor
);
4927 this.setAlignment( config
.align
|| 'center' );
4928 this.setPosition( config
.position
|| 'below' );
4929 this.$body
.addClass( 'oo-ui-popupWidget-body' );
4930 this.$anchor
.addClass( 'oo-ui-popupWidget-anchor' );
4932 .addClass( 'oo-ui-popupWidget-popup' )
4933 .append( this.$body
);
4935 .addClass( 'oo-ui-popupWidget' )
4936 .append( this.$popup
, this.$anchor
);
4937 // Move content, which was added to #$element by OO.ui.Widget, to the body
4938 // FIXME This is gross, we should use '$body' or something for the config
4939 if ( config
.$content
instanceof jQuery
) {
4940 this.$body
.append( config
.$content
);
4943 if ( config
.padded
) {
4944 this.$body
.addClass( 'oo-ui-popupWidget-body-padded' );
4947 if ( config
.head
) {
4948 this.closeButton
= new OO
.ui
.ButtonWidget( { framed
: false, icon
: 'close' } );
4949 this.closeButton
.connect( this, { click
: 'onCloseButtonClick' } );
4950 this.$head
= $( '<div>' )
4951 .addClass( 'oo-ui-popupWidget-head' )
4952 .append( this.$label
, this.closeButton
.$element
);
4953 this.$popup
.prepend( this.$head
);
4956 if ( config
.$footer
) {
4957 this.$footer
= $( '<div>' )
4958 .addClass( 'oo-ui-popupWidget-footer' )
4959 .append( config
.$footer
);
4960 this.$popup
.append( this.$footer
);
4963 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
4964 // that reference properties not initialized at that time of parent class construction
4965 // TODO: Find a better way to handle post-constructor setup
4966 this.visible
= false;
4967 this.$element
.addClass( 'oo-ui-element-hidden' );
4972 OO
.inheritClass( OO
.ui
.PopupWidget
, OO
.ui
.Widget
);
4973 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.LabelElement
);
4974 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.ClippableElement
);
4975 OO
.mixinClass( OO
.ui
.PopupWidget
, OO
.ui
.mixin
.FloatableElement
);
4982 * The popup is ready: it is visible and has been positioned and clipped.
4988 * Handles mouse down events.
4991 * @param {MouseEvent} e Mouse down event
4993 OO
.ui
.PopupWidget
.prototype.onMouseDown = function ( e
) {
4996 !OO
.ui
.contains( this.$element
.add( this.$autoCloseIgnore
).get(), e
.target
, true )
4998 this.toggle( false );
5003 * Bind mouse down listener.
5007 OO
.ui
.PopupWidget
.prototype.bindMouseDownListener = function () {
5008 // Capture clicks outside popup
5009 this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler
, true );
5013 * Handles close button click events.
5017 OO
.ui
.PopupWidget
.prototype.onCloseButtonClick = function () {
5018 if ( this.isVisible() ) {
5019 this.toggle( false );
5024 * Unbind mouse down listener.
5028 OO
.ui
.PopupWidget
.prototype.unbindMouseDownListener = function () {
5029 this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler
, true );
5033 * Handles key down events.
5036 * @param {KeyboardEvent} e Key down event
5038 OO
.ui
.PopupWidget
.prototype.onDocumentKeyDown = function ( e
) {
5040 e
.which
=== OO
.ui
.Keys
.ESCAPE
&&
5043 this.toggle( false );
5045 e
.stopPropagation();
5050 * Bind key down listener.
5054 OO
.ui
.PopupWidget
.prototype.bindKeyDownListener = function () {
5055 this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5059 * Unbind key down listener.
5063 OO
.ui
.PopupWidget
.prototype.unbindKeyDownListener = function () {
5064 this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler
, true );
5068 * Show, hide, or toggle the visibility of the anchor.
5070 * @param {boolean} [show] Show anchor, omit to toggle
5072 OO
.ui
.PopupWidget
.prototype.toggleAnchor = function ( show
) {
5073 show
= show
=== undefined ? !this.anchored
: !!show
;
5075 if ( this.anchored
!== show
) {
5077 this.$element
.addClass( 'oo-ui-popupWidget-anchored' );
5078 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5080 this.$element
.removeClass( 'oo-ui-popupWidget-anchored' );
5081 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5083 this.anchored
= show
;
5087 * Change which edge the anchor appears on.
5089 * @param {string} edge 'top', 'bottom', 'start' or 'end'
5091 OO
.ui
.PopupWidget
.prototype.setAnchorEdge = function ( edge
) {
5092 if ( [ 'top', 'bottom', 'start', 'end' ].indexOf( edge
) === -1 ) {
5093 throw new Error( 'Invalid value for edge: ' + edge
);
5095 if ( this.anchorEdge
!== null ) {
5096 this.$element
.removeClass( 'oo-ui-popupWidget-anchored-' + this.anchorEdge
);
5098 this.anchorEdge
= edge
;
5099 if ( this.anchored
) {
5100 this.$element
.addClass( 'oo-ui-popupWidget-anchored-' + edge
);
5105 * Check if the anchor is visible.
5107 * @return {boolean} Anchor is visible
5109 OO
.ui
.PopupWidget
.prototype.hasAnchor = function () {
5110 return this.anchored
;
5114 * Toggle visibility of the popup. The popup is initially hidden and must be shown by calling
5115 * `.toggle( true )` after its #$element is attached to the DOM.
5117 * Do not show the popup while it is not attached to the DOM. The calculations required to display
5118 * it in the right place and with the right dimensions only work correctly while it is attached.
5119 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
5120 * strictly enforced, so currently it only generates a warning in the browser console.
5125 OO
.ui
.PopupWidget
.prototype.toggle = function ( show
) {
5127 show
= show
=== undefined ? !this.isVisible() : !!show
;
5129 change
= show
!== this.isVisible();
5131 if ( show
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
5132 OO
.ui
.warnDeprecation( 'PopupWidget#toggle: Before calling this method, the popup must be attached to the DOM.' );
5133 this.warnedUnattached
= true;
5135 if ( show
&& !this.$floatableContainer
&& this.isElementAttached() ) {
5136 // Fall back to the parent node if the floatableContainer is not set
5137 this.setFloatableContainer( this.$element
.parent() );
5141 OO
.ui
.PopupWidget
.parent
.prototype.toggle
.call( this, show
);
5144 this.togglePositioning( show
&& !!this.$floatableContainer
);
5147 if ( this.autoClose
) {
5148 this.bindMouseDownListener();
5149 this.bindKeyDownListener();
5151 this.updateDimensions();
5152 this.toggleClipping( true );
5153 this.emit( 'ready' );
5155 this.toggleClipping( false );
5156 if ( this.autoClose
) {
5157 this.unbindMouseDownListener();
5158 this.unbindKeyDownListener();
5167 * Set the size of the popup.
5169 * Changing the size may also change the popup's position depending on the alignment.
5171 * @param {number} width Width in pixels
5172 * @param {number} height Height in pixels
5173 * @param {boolean} [transition=false] Use a smooth transition
5176 OO
.ui
.PopupWidget
.prototype.setSize = function ( width
, height
, transition
) {
5178 this.height
= height
!== undefined ? height
: null;
5179 if ( this.isVisible() ) {
5180 this.updateDimensions( transition
);
5185 * Update the size and position.
5187 * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will
5188 * be called automatically.
5190 * @param {boolean} [transition=false] Use a smooth transition
5193 OO
.ui
.PopupWidget
.prototype.updateDimensions = function ( transition
) {
5196 // Prevent transition from being interrupted
5197 clearTimeout( this.transitionTimeout
);
5199 // Enable transition
5200 this.$element
.addClass( 'oo-ui-popupWidget-transitioning' );
5206 // Prevent transitioning after transition is complete
5207 this.transitionTimeout
= setTimeout( function () {
5208 widget
.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5211 // Prevent transitioning immediately
5212 this.$element
.removeClass( 'oo-ui-popupWidget-transitioning' );
5219 OO
.ui
.PopupWidget
.prototype.computePosition = function () {
5220 var direction
, align
, vertical
, start
, end
, near
, far
, sizeProp
, popupSize
, anchorSize
, anchorPos
,
5221 anchorOffset
, anchorMargin
, parentPosition
, positionProp
, positionAdjustment
, floatablePos
,
5222 offsetParentPos
, containerPos
,
5224 anchorCss
= { left
: '', right
: '', top
: '', bottom
: '' },
5227 'force-left': 'backwards',
5228 'force-right': 'forwards'
5231 'force-left': 'forwards',
5232 'force-right': 'backwards'
5244 backwards
: this.anchored
? 'before' : 'end'
5252 if ( !this.$container
) {
5253 // Lazy-initialize $container if not specified in constructor
5254 this.$container
= $( this.getClosestScrollableElementContainer() );
5256 direction
= this.$container
.css( 'direction' );
5258 // Set height and width before we do anything else, since it might cause our measurements
5259 // to change (e.g. due to scrollbars appearing or disappearing), and it also affects centering
5262 height
: this.height
!== null ? this.height
: 'auto'
5265 align
= alignMap
[ direction
][ this.align
] || this.align
;
5266 // If the popup is positioned before or after, then the anchor positioning is vertical, otherwise horizontal
5267 vertical
= this.popupPosition
=== 'before' || this.popupPosition
=== 'after';
5268 start
= vertical
? 'top' : ( direction
=== 'rtl' ? 'right' : 'left' );
5269 end
= vertical
? 'bottom' : ( direction
=== 'rtl' ? 'left' : 'right' );
5270 near
= vertical
? 'top' : 'left';
5271 far
= vertical
? 'bottom' : 'right';
5272 sizeProp
= vertical
? 'Height' : 'Width';
5273 popupSize
= vertical
? ( this.height
|| this.$popup
.height() ) : this.width
;
5275 this.setAnchorEdge( anchorEdgeMap
[ this.popupPosition
] );
5276 this.horizontalPosition
= vertical
? this.popupPosition
: hPosMap
[ align
];
5277 this.verticalPosition
= vertical
? vPosMap
[ align
] : this.popupPosition
;
5280 parentPosition
= OO
.ui
.mixin
.FloatableElement
.prototype.computePosition
.call( this );
5281 // Find out which property FloatableElement used for positioning, and adjust that value
5282 positionProp
= vertical
?
5283 ( parentPosition
.top
!== '' ? 'top' : 'bottom' ) :
5284 ( parentPosition
.left
!== '' ? 'left' : 'right' );
5286 // Figure out where the near and far edges of the popup and $floatableContainer are
5287 floatablePos
= this.$floatableContainer
.offset();
5288 floatablePos
[ far
] = floatablePos
[ near
] + this.$floatableContainer
[ 'outer' + sizeProp
]();
5289 // Measure where the offsetParent is and compute our position based on that and parentPosition
5290 offsetParentPos
= this.$element
.offsetParent().offset();
5292 if ( positionProp
=== near
) {
5293 popupPos
[ near
] = offsetParentPos
[ near
] + parentPosition
[ near
];
5294 popupPos
[ far
] = popupPos
[ near
] + popupSize
;
5296 popupPos
[ far
] = offsetParentPos
[ near
] +
5297 this.$element
.offsetParent()[ 'inner' + sizeProp
]() - parentPosition
[ far
];
5298 popupPos
[ near
] = popupPos
[ far
] - popupSize
;
5301 if ( this.anchored
) {
5302 // Position the anchor (which is positioned relative to the popup) to point to $floatableContainer
5303 anchorPos
= ( floatablePos
[ start
] + floatablePos
[ end
] ) / 2;
5304 anchorOffset
= ( start
=== far
? -1 : 1 ) * ( anchorPos
- popupPos
[ start
] );
5306 // If the anchor is less than 2*anchorSize from either edge, move the popup to make more space
5307 // this.$anchor.width()/height() returns 0 because of the CSS trickery we use, so use scrollWidth/Height
5308 anchorSize
= this.$anchor
[ 0 ][ 'scroll' + sizeProp
];
5309 anchorMargin
= parseFloat( this.$anchor
.css( 'margin-' + start
) );
5310 if ( anchorOffset
+ anchorMargin
< 2 * anchorSize
) {
5311 // Not enough space for the anchor on the start side; pull the popup startwards
5312 positionAdjustment
= ( positionProp
=== start
? -1 : 1 ) *
5313 ( 2 * anchorSize
- ( anchorOffset
+ anchorMargin
) );
5314 } else if ( anchorOffset
+ anchorMargin
> popupSize
- 2 * anchorSize
) {
5315 // Not enough space for the anchor on the end side; pull the popup endwards
5316 positionAdjustment
= ( positionProp
=== end
? -1 : 1 ) *
5317 ( anchorOffset
+ anchorMargin
- ( popupSize
- 2 * anchorSize
) );
5319 positionAdjustment
= 0;
5322 positionAdjustment
= 0;
5325 // Check if the popup will go beyond the edge of this.$container
5326 containerPos
= this.$container
.offset();
5327 containerPos
[ far
] = containerPos
[ near
] + this.$container
[ 'inner' + sizeProp
]();
5328 // Take into account how much the popup will move because of the adjustments we're going to make
5329 popupPos
[ near
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5330 popupPos
[ far
] += ( positionProp
=== near
? 1 : -1 ) * positionAdjustment
;
5331 if ( containerPos
[ near
] + this.containerPadding
> popupPos
[ near
] ) {
5332 // Popup goes beyond the near (left/top) edge, move it to the right/bottom
5333 positionAdjustment
+= ( positionProp
=== near
? 1 : -1 ) *
5334 ( containerPos
[ near
] + this.containerPadding
- popupPos
[ near
] );
5335 } else if ( containerPos
[ far
] - this.containerPadding
< popupPos
[ far
] ) {
5336 // Popup goes beyond the far (right/bottom) edge, move it to the left/top
5337 positionAdjustment
+= ( positionProp
=== far
? 1 : -1 ) *
5338 ( popupPos
[ far
] - ( containerPos
[ far
] - this.containerPadding
) );
5341 if ( this.anchored
) {
5342 // Adjust anchorOffset for positionAdjustment
5343 anchorOffset
+= ( positionProp
=== start
? -1 : 1 ) * positionAdjustment
;
5345 // Position the anchor
5346 anchorCss
[ start
] = anchorOffset
;
5347 this.$anchor
.css( anchorCss
);
5350 // Move the popup if needed
5351 parentPosition
[ positionProp
] += positionAdjustment
;
5353 return parentPosition
;
5357 * Set popup alignment
5359 * @param {string} [align=center] Alignment of the popup, `center`, `force-left`, `force-right`,
5360 * `backwards` or `forwards`.
5362 OO
.ui
.PopupWidget
.prototype.setAlignment = function ( align
) {
5363 // Validate alignment
5364 if ( [ 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align
) > -1 ) {
5367 this.align
= 'center';
5373 * Get popup alignment
5375 * @return {string} Alignment of the popup, `center`, `force-left`, `force-right`,
5376 * `backwards` or `forwards`.
5378 OO
.ui
.PopupWidget
.prototype.getAlignment = function () {
5383 * Change the positioning of the popup.
5385 * @param {string} position 'above', 'below', 'before' or 'after'
5387 OO
.ui
.PopupWidget
.prototype.setPosition = function ( position
) {
5388 if ( [ 'above', 'below', 'before', 'after' ].indexOf( position
) === -1 ) {
5391 this.popupPosition
= position
;
5396 * Get popup positioning.
5398 * @return {string} 'above', 'below', 'before' or 'after'
5400 OO
.ui
.PopupWidget
.prototype.getPosition = function () {
5401 return this.popupPosition
;
5405 * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}.
5406 * A popup is a container for content. It is overlaid and positioned absolutely. By default, each
5407 * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin.
5408 * See {@link OO.ui.PopupWidget PopupWidget} for an example.
5414 * @param {Object} [config] Configuration options
5415 * @cfg {Object} [popup] Configuration to pass to popup
5416 * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus
5418 OO
.ui
.mixin
.PopupElement
= function OoUiMixinPopupElement( config
) {
5419 // Configuration initialization
5420 config
= config
|| {};
5423 this.popup
= new OO
.ui
.PopupWidget( $.extend(
5426 $floatableContainer
: this.$element
5430 $autoCloseIgnore
: this.$element
.add( config
.popup
&& config
.popup
.$autoCloseIgnore
)
5440 * @return {OO.ui.PopupWidget} Popup widget
5442 OO
.ui
.mixin
.PopupElement
.prototype.getPopup = function () {
5447 * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget},
5448 * which is used to display additional information or options.
5451 * // Example of a popup button.
5452 * var popupButton = new OO.ui.PopupButtonWidget( {
5453 * label: 'Popup button with options',
5456 * $content: $( '<p>Additional options here.</p>' ),
5458 * align: 'force-left'
5461 * // Append the button to the DOM.
5462 * $( 'body' ).append( popupButton.$element );
5465 * @extends OO.ui.ButtonWidget
5466 * @mixins OO.ui.mixin.PopupElement
5469 * @param {Object} [config] Configuration options
5470 * @cfg {jQuery} [$overlay] Render the popup into a separate layer. This configuration is useful in cases where
5471 * the expanded popup is larger than its containing `<div>`. The specified overlay layer is usually on top of the
5472 * containing `<div>` and has a larger area. By default, the popup uses relative positioning.
5473 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
5475 OO
.ui
.PopupButtonWidget
= function OoUiPopupButtonWidget( config
) {
5476 // Configuration initialization
5477 config
= config
|| {};
5479 // Parent constructor
5480 OO
.ui
.PopupButtonWidget
.parent
.call( this, config
);
5482 // Mixin constructors
5483 OO
.ui
.mixin
.PopupElement
.call( this, config
);
5486 this.$overlay
= config
.$overlay
|| this.$element
;
5489 this.connect( this, { click
: 'onAction' } );
5493 .addClass( 'oo-ui-popupButtonWidget' )
5494 .attr( 'aria-haspopup', 'true' );
5496 .addClass( 'oo-ui-popupButtonWidget-popup' )
5497 .toggleClass( 'oo-ui-popupButtonWidget-framed-popup', this.isFramed() )
5498 .toggleClass( 'oo-ui-popupButtonWidget-frameless-popup', !this.isFramed() );
5499 this.$overlay
.append( this.popup
.$element
);
5504 OO
.inheritClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.ButtonWidget
);
5505 OO
.mixinClass( OO
.ui
.PopupButtonWidget
, OO
.ui
.mixin
.PopupElement
);
5510 * Handle the button action being triggered.
5514 OO
.ui
.PopupButtonWidget
.prototype.onAction = function () {
5515 this.popup
.toggle();
5519 * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement.
5521 * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable.
5526 * @mixins OO.ui.mixin.GroupElement
5529 * @param {Object} [config] Configuration options
5531 OO
.ui
.mixin
.GroupWidget
= function OoUiMixinGroupWidget( config
) {
5532 // Mixin constructors
5533 OO
.ui
.mixin
.GroupElement
.call( this, config
);
5538 OO
.mixinClass( OO
.ui
.mixin
.GroupWidget
, OO
.ui
.mixin
.GroupElement
);
5543 * Set the disabled state of the widget.
5545 * This will also update the disabled state of child widgets.
5547 * @param {boolean} disabled Disable widget
5550 OO
.ui
.mixin
.GroupWidget
.prototype.setDisabled = function ( disabled
) {
5554 // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget
5555 OO
.ui
.Widget
.prototype.setDisabled
.call( this, disabled
);
5557 // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor
5559 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
5560 this.items
[ i
].updateDisabled();
5568 * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget.
5570 * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This
5571 * allows bidirectional communication.
5573 * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable.
5581 OO
.ui
.mixin
.ItemWidget
= function OoUiMixinItemWidget() {
5588 * Check if widget is disabled.
5590 * Checks parent if present, making disabled state inheritable.
5592 * @return {boolean} Widget is disabled
5594 OO
.ui
.mixin
.ItemWidget
.prototype.isDisabled = function () {
5595 return this.disabled
||
5596 ( this.elementGroup
instanceof OO
.ui
.Widget
&& this.elementGroup
.isDisabled() );
5600 * Set group element is in.
5602 * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none
5605 OO
.ui
.mixin
.ItemWidget
.prototype.setElementGroup = function ( group
) {
5607 // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element
5608 OO
.ui
.Element
.prototype.setElementGroup
.call( this, group
);
5610 // Initialize item disabled states
5611 this.updateDisabled();
5617 * OptionWidgets are special elements that can be selected and configured with data. The
5618 * data is often unique for each option, but it does not have to be. OptionWidgets are used
5619 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
5620 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
5622 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5625 * @extends OO.ui.Widget
5626 * @mixins OO.ui.mixin.ItemWidget
5627 * @mixins OO.ui.mixin.LabelElement
5628 * @mixins OO.ui.mixin.FlaggedElement
5629 * @mixins OO.ui.mixin.AccessKeyedElement
5632 * @param {Object} [config] Configuration options
5634 OO
.ui
.OptionWidget
= function OoUiOptionWidget( config
) {
5635 // Configuration initialization
5636 config
= config
|| {};
5638 // Parent constructor
5639 OO
.ui
.OptionWidget
.parent
.call( this, config
);
5641 // Mixin constructors
5642 OO
.ui
.mixin
.ItemWidget
.call( this );
5643 OO
.ui
.mixin
.LabelElement
.call( this, config
);
5644 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
5645 OO
.ui
.mixin
.AccessKeyedElement
.call( this, config
);
5648 this.selected
= false;
5649 this.highlighted
= false;
5650 this.pressed
= false;
5654 .data( 'oo-ui-optionWidget', this )
5655 // Allow programmatic focussing (and by accesskey), but not tabbing
5656 .attr( 'tabindex', '-1' )
5657 .attr( 'role', 'option' )
5658 .attr( 'aria-selected', 'false' )
5659 .addClass( 'oo-ui-optionWidget' )
5660 .append( this.$label
);
5665 OO
.inheritClass( OO
.ui
.OptionWidget
, OO
.ui
.Widget
);
5666 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.ItemWidget
);
5667 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.LabelElement
);
5668 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.FlaggedElement
);
5669 OO
.mixinClass( OO
.ui
.OptionWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
5671 /* Static Properties */
5674 * Whether this option can be selected. See #setSelected.
5678 * @property {boolean}
5680 OO
.ui
.OptionWidget
.static.selectable
= true;
5683 * Whether this option can be highlighted. See #setHighlighted.
5687 * @property {boolean}
5689 OO
.ui
.OptionWidget
.static.highlightable
= true;
5692 * Whether this option can be pressed. See #setPressed.
5696 * @property {boolean}
5698 OO
.ui
.OptionWidget
.static.pressable
= true;
5701 * Whether this option will be scrolled into view when it is selected.
5705 * @property {boolean}
5707 OO
.ui
.OptionWidget
.static.scrollIntoViewOnSelect
= false;
5712 * Check if the option can be selected.
5714 * @return {boolean} Item is selectable
5716 OO
.ui
.OptionWidget
.prototype.isSelectable = function () {
5717 return this.constructor.static.selectable
&& !this.isDisabled() && this.isVisible();
5721 * Check if the option can be highlighted. A highlight indicates that the option
5722 * may be selected when a user presses enter or clicks. Disabled items cannot
5725 * @return {boolean} Item is highlightable
5727 OO
.ui
.OptionWidget
.prototype.isHighlightable = function () {
5728 return this.constructor.static.highlightable
&& !this.isDisabled() && this.isVisible();
5732 * Check if the option can be pressed. The pressed state occurs when a user mouses
5733 * down on an item, but has not yet let go of the mouse.
5735 * @return {boolean} Item is pressable
5737 OO
.ui
.OptionWidget
.prototype.isPressable = function () {
5738 return this.constructor.static.pressable
&& !this.isDisabled() && this.isVisible();
5742 * Check if the option is selected.
5744 * @return {boolean} Item is selected
5746 OO
.ui
.OptionWidget
.prototype.isSelected = function () {
5747 return this.selected
;
5751 * Check if the option is highlighted. A highlight indicates that the
5752 * item may be selected when a user presses enter or clicks.
5754 * @return {boolean} Item is highlighted
5756 OO
.ui
.OptionWidget
.prototype.isHighlighted = function () {
5757 return this.highlighted
;
5761 * Check if the option is pressed. The pressed state occurs when a user mouses
5762 * down on an item, but has not yet let go of the mouse. The item may appear
5763 * selected, but it will not be selected until the user releases the mouse.
5765 * @return {boolean} Item is pressed
5767 OO
.ui
.OptionWidget
.prototype.isPressed = function () {
5768 return this.pressed
;
5772 * Set the option’s selected state. In general, all modifications to the selection
5773 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
5774 * method instead of this method.
5776 * @param {boolean} [state=false] Select option
5779 OO
.ui
.OptionWidget
.prototype.setSelected = function ( state
) {
5780 if ( this.constructor.static.selectable
) {
5781 this.selected
= !!state
;
5783 .toggleClass( 'oo-ui-optionWidget-selected', state
)
5784 .attr( 'aria-selected', state
.toString() );
5785 if ( state
&& this.constructor.static.scrollIntoViewOnSelect
) {
5786 this.scrollElementIntoView();
5788 this.updateThemeClasses();
5794 * Set the option’s highlighted state. In general, all programmatic
5795 * modifications to the highlight should be handled by the
5796 * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )}
5797 * method instead of this method.
5799 * @param {boolean} [state=false] Highlight option
5802 OO
.ui
.OptionWidget
.prototype.setHighlighted = function ( state
) {
5803 if ( this.constructor.static.highlightable
) {
5804 this.highlighted
= !!state
;
5805 this.$element
.toggleClass( 'oo-ui-optionWidget-highlighted', state
);
5806 this.updateThemeClasses();
5812 * Set the option’s pressed state. In general, all
5813 * programmatic modifications to the pressed state should be handled by the
5814 * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )}
5815 * method instead of this method.
5817 * @param {boolean} [state=false] Press option
5820 OO
.ui
.OptionWidget
.prototype.setPressed = function ( state
) {
5821 if ( this.constructor.static.pressable
) {
5822 this.pressed
= !!state
;
5823 this.$element
.toggleClass( 'oo-ui-optionWidget-pressed', state
);
5824 this.updateThemeClasses();
5830 * Get text to match search strings against.
5832 * The default implementation returns the label text, but subclasses
5833 * can override this to provide more complex behavior.
5835 * @return {string|boolean} String to match search string against
5837 OO
.ui
.OptionWidget
.prototype.getMatchText = function () {
5838 var label
= this.getLabel();
5839 return typeof label
=== 'string' ? label
: this.$label
.text();
5843 * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of
5844 * select widgets, including {@link OO.ui.ButtonSelectWidget button selects},
5845 * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget
5848 * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more
5849 * information, please see the [OOjs UI documentation on MediaWiki][1].
5852 * // Example of a select widget with three options
5853 * var select = new OO.ui.SelectWidget( {
5855 * new OO.ui.OptionWidget( {
5857 * label: 'Option One',
5859 * new OO.ui.OptionWidget( {
5861 * label: 'Option Two',
5863 * new OO.ui.OptionWidget( {
5865 * label: 'Option Three',
5869 * $( 'body' ).append( select.$element );
5871 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5875 * @extends OO.ui.Widget
5876 * @mixins OO.ui.mixin.GroupWidget
5879 * @param {Object} [config] Configuration options
5880 * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select.
5881 * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See
5882 * the [OOjs UI documentation on MediaWiki] [2] for examples.
5883 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
5885 OO
.ui
.SelectWidget
= function OoUiSelectWidget( config
) {
5886 // Configuration initialization
5887 config
= config
|| {};
5889 // Parent constructor
5890 OO
.ui
.SelectWidget
.parent
.call( this, config
);
5892 // Mixin constructors
5893 OO
.ui
.mixin
.GroupWidget
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
5896 this.pressed
= false;
5897 this.selecting
= null;
5898 this.onMouseUpHandler
= this.onMouseUp
.bind( this );
5899 this.onMouseMoveHandler
= this.onMouseMove
.bind( this );
5900 this.onKeyDownHandler
= this.onKeyDown
.bind( this );
5901 this.onKeyPressHandler
= this.onKeyPress
.bind( this );
5902 this.keyPressBuffer
= '';
5903 this.keyPressBufferTimer
= null;
5904 this.blockMouseOverEvents
= 0;
5907 this.connect( this, {
5911 focusin
: this.onFocus
.bind( this ),
5912 mousedown
: this.onMouseDown
.bind( this ),
5913 mouseover
: this.onMouseOver
.bind( this ),
5914 mouseleave
: this.onMouseLeave
.bind( this )
5919 .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' )
5920 .attr( 'role', 'listbox' );
5921 this.setFocusOwner( this.$element
);
5922 if ( Array
.isArray( config
.items
) ) {
5923 this.addItems( config
.items
);
5929 OO
.inheritClass( OO
.ui
.SelectWidget
, OO
.ui
.Widget
);
5930 OO
.mixinClass( OO
.ui
.SelectWidget
, OO
.ui
.mixin
.GroupWidget
);
5937 * A `highlight` event is emitted when the highlight is changed with the #highlightItem method.
5939 * @param {OO.ui.OptionWidget|null} item Highlighted item
5945 * A `press` event is emitted when the #pressItem method is used to programmatically modify the
5946 * pressed state of an option.
5948 * @param {OO.ui.OptionWidget|null} item Pressed item
5954 * A `select` event is emitted when the selection is modified programmatically with the #selectItem method.
5956 * @param {OO.ui.OptionWidget|null} item Selected item
5961 * A `choose` event is emitted when an item is chosen with the #chooseItem method.
5962 * @param {OO.ui.OptionWidget} item Chosen item
5968 * An `add` event is emitted when options are added to the select with the #addItems method.
5970 * @param {OO.ui.OptionWidget[]} items Added items
5971 * @param {number} index Index of insertion point
5977 * A `remove` event is emitted when options are removed from the select with the #clearItems
5978 * or #removeItems methods.
5980 * @param {OO.ui.OptionWidget[]} items Removed items
5986 * Handle focus events
5989 * @param {jQuery.Event} event
5991 OO
.ui
.SelectWidget
.prototype.onFocus = function ( event
) {
5993 if ( event
.target
=== this.$element
[ 0 ] ) {
5994 // This widget was focussed, e.g. by the user tabbing to it.
5995 // The styles for focus state depend on one of the items being selected.
5996 if ( !this.getSelectedItem() ) {
5997 item
= this.getFirstSelectableItem();
6000 // One of the options got focussed (and the event bubbled up here).
6001 // They can't be tabbed to, but they can be activated using accesskeys.
6002 item
= this.getTargetItem( event
);
6006 if ( item
.constructor.static.highlightable
) {
6007 this.highlightItem( item
);
6009 this.selectItem( item
);
6013 if ( event
.target
!== this.$element
[ 0 ] ) {
6014 this.$focusOwner
.focus();
6019 * Handle mouse down events.
6022 * @param {jQuery.Event} e Mouse down event
6024 OO
.ui
.SelectWidget
.prototype.onMouseDown = function ( e
) {
6027 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
6028 this.togglePressed( true );
6029 item
= this.getTargetItem( e
);
6030 if ( item
&& item
.isSelectable() ) {
6031 this.pressItem( item
);
6032 this.selecting
= item
;
6033 this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler
, true );
6034 this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6041 * Handle mouse up events.
6044 * @param {MouseEvent} e Mouse up event
6046 OO
.ui
.SelectWidget
.prototype.onMouseUp = function ( e
) {
6049 this.togglePressed( false );
6050 if ( !this.selecting
) {
6051 item
= this.getTargetItem( e
);
6052 if ( item
&& item
.isSelectable() ) {
6053 this.selecting
= item
;
6056 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
&& this.selecting
) {
6057 this.pressItem( null );
6058 this.chooseItem( this.selecting
);
6059 this.selecting
= null;
6062 this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler
, true );
6063 this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler
, true );
6069 * Handle mouse move events.
6072 * @param {MouseEvent} e Mouse move event
6074 OO
.ui
.SelectWidget
.prototype.onMouseMove = function ( e
) {
6077 if ( !this.isDisabled() && this.pressed
) {
6078 item
= this.getTargetItem( e
);
6079 if ( item
&& item
!== this.selecting
&& item
.isSelectable() ) {
6080 this.pressItem( item
);
6081 this.selecting
= item
;
6087 * Handle mouse over events.
6090 * @param {jQuery.Event} e Mouse over event
6092 OO
.ui
.SelectWidget
.prototype.onMouseOver = function ( e
) {
6094 if ( this.blockMouseOverEvents
) {
6097 if ( !this.isDisabled() ) {
6098 item
= this.getTargetItem( e
);
6099 this.highlightItem( item
&& item
.isHighlightable() ? item
: null );
6105 * Handle mouse leave events.
6108 * @param {jQuery.Event} e Mouse over event
6110 OO
.ui
.SelectWidget
.prototype.onMouseLeave = function () {
6111 if ( !this.isDisabled() ) {
6112 this.highlightItem( null );
6118 * Handle key down events.
6121 * @param {KeyboardEvent} e Key down event
6123 OO
.ui
.SelectWidget
.prototype.onKeyDown = function ( e
) {
6126 currentItem
= this.getHighlightedItem() || this.getSelectedItem();
6128 if ( !this.isDisabled() && this.isVisible() ) {
6129 switch ( e
.keyCode
) {
6130 case OO
.ui
.Keys
.ENTER
:
6131 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6132 // Was only highlighted, now let's select it. No-op if already selected.
6133 this.chooseItem( currentItem
);
6138 case OO
.ui
.Keys
.LEFT
:
6139 this.clearKeyPressBuffer();
6140 nextItem
= this.getRelativeSelectableItem( currentItem
, -1 );
6143 case OO
.ui
.Keys
.DOWN
:
6144 case OO
.ui
.Keys
.RIGHT
:
6145 this.clearKeyPressBuffer();
6146 nextItem
= this.getRelativeSelectableItem( currentItem
, 1 );
6149 case OO
.ui
.Keys
.ESCAPE
:
6150 case OO
.ui
.Keys
.TAB
:
6151 if ( currentItem
&& currentItem
.constructor.static.highlightable
) {
6152 currentItem
.setHighlighted( false );
6154 this.unbindKeyDownListener();
6155 this.unbindKeyPressListener();
6156 // Don't prevent tabbing away / defocusing
6162 if ( nextItem
.constructor.static.highlightable
) {
6163 this.highlightItem( nextItem
);
6165 this.chooseItem( nextItem
);
6167 this.scrollItemIntoView( nextItem
);
6172 e
.stopPropagation();
6178 * Bind key down listener.
6182 OO
.ui
.SelectWidget
.prototype.bindKeyDownListener = function () {
6183 this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler
, true );
6187 * Unbind key down listener.
6191 OO
.ui
.SelectWidget
.prototype.unbindKeyDownListener = function () {
6192 this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler
, true );
6196 * Scroll item into view, preventing spurious mouse highlight actions from happening.
6198 * @param {OO.ui.OptionWidget} item Item to scroll into view
6200 OO
.ui
.SelectWidget
.prototype.scrollItemIntoView = function ( item
) {
6202 // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling
6203 // and around 100-150 ms after it is finished.
6204 this.blockMouseOverEvents
++;
6205 item
.scrollElementIntoView().done( function () {
6206 setTimeout( function () {
6207 widget
.blockMouseOverEvents
--;
6213 * Clear the key-press buffer
6217 OO
.ui
.SelectWidget
.prototype.clearKeyPressBuffer = function () {
6218 if ( this.keyPressBufferTimer
) {
6219 clearTimeout( this.keyPressBufferTimer
);
6220 this.keyPressBufferTimer
= null;
6222 this.keyPressBuffer
= '';
6226 * Handle key press events.
6229 * @param {KeyboardEvent} e Key press event
6231 OO
.ui
.SelectWidget
.prototype.onKeyPress = function ( e
) {
6232 var c
, filter
, item
;
6234 if ( !e
.charCode
) {
6235 if ( e
.keyCode
=== OO
.ui
.Keys
.BACKSPACE
&& this.keyPressBuffer
!== '' ) {
6236 this.keyPressBuffer
= this.keyPressBuffer
.substr( 0, this.keyPressBuffer
.length
- 1 );
6241 if ( String
.fromCodePoint
) {
6242 c
= String
.fromCodePoint( e
.charCode
);
6244 c
= String
.fromCharCode( e
.charCode
);
6247 if ( this.keyPressBufferTimer
) {
6248 clearTimeout( this.keyPressBufferTimer
);
6250 this.keyPressBufferTimer
= setTimeout( this.clearKeyPressBuffer
.bind( this ), 1500 );
6252 item
= this.getHighlightedItem() || this.getSelectedItem();
6254 if ( this.keyPressBuffer
=== c
) {
6255 // Common (if weird) special case: typing "xxxx" will cycle through all
6256 // the items beginning with "x".
6258 item
= this.getRelativeSelectableItem( item
, 1 );
6261 this.keyPressBuffer
+= c
;
6264 filter
= this.getItemMatcher( this.keyPressBuffer
, false );
6265 if ( !item
|| !filter( item
) ) {
6266 item
= this.getRelativeSelectableItem( item
, 1, filter
);
6269 if ( this.isVisible() && item
.constructor.static.highlightable
) {
6270 this.highlightItem( item
);
6272 this.chooseItem( item
);
6274 this.scrollItemIntoView( item
);
6278 e
.stopPropagation();
6282 * Get a matcher for the specific string
6285 * @param {string} s String to match against items
6286 * @param {boolean} [exact=false] Only accept exact matches
6287 * @return {Function} function ( OO.ui.OptionWidget ) => boolean
6289 OO
.ui
.SelectWidget
.prototype.getItemMatcher = function ( s
, exact
) {
6292 if ( s
.normalize
) {
6295 s
= exact
? s
.trim() : s
.replace( /^\s+/, '' );
6296 re
= '^\\s*' + s
.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' );
6300 re
= new RegExp( re
, 'i' );
6301 return function ( item
) {
6302 var matchText
= item
.getMatchText();
6303 if ( matchText
.normalize
) {
6304 matchText
= matchText
.normalize();
6306 return re
.test( matchText
);
6311 * Bind key press listener.
6315 OO
.ui
.SelectWidget
.prototype.bindKeyPressListener = function () {
6316 this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler
, true );
6320 * Unbind key down listener.
6322 * If you override this, be sure to call this.clearKeyPressBuffer() from your
6327 OO
.ui
.SelectWidget
.prototype.unbindKeyPressListener = function () {
6328 this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler
, true );
6329 this.clearKeyPressBuffer();
6333 * Visibility change handler
6336 * @param {boolean} visible
6338 OO
.ui
.SelectWidget
.prototype.onToggle = function ( visible
) {
6340 this.clearKeyPressBuffer();
6345 * Get the closest item to a jQuery.Event.
6348 * @param {jQuery.Event} e
6349 * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found
6351 OO
.ui
.SelectWidget
.prototype.getTargetItem = function ( e
) {
6352 return $( e
.target
).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null;
6356 * Get selected item.
6358 * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected
6360 OO
.ui
.SelectWidget
.prototype.getSelectedItem = function () {
6363 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6364 if ( this.items
[ i
].isSelected() ) {
6365 return this.items
[ i
];
6372 * Get highlighted item.
6374 * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted
6376 OO
.ui
.SelectWidget
.prototype.getHighlightedItem = function () {
6379 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6380 if ( this.items
[ i
].isHighlighted() ) {
6381 return this.items
[ i
];
6388 * Toggle pressed state.
6390 * Press is a state that occurs when a user mouses down on an item, but
6391 * has not yet let go of the mouse. The item may appear selected, but it will not be selected
6392 * until the user releases the mouse.
6394 * @param {boolean} pressed An option is being pressed
6396 OO
.ui
.SelectWidget
.prototype.togglePressed = function ( pressed
) {
6397 if ( pressed
=== undefined ) {
6398 pressed
= !this.pressed
;
6400 if ( pressed
!== this.pressed
) {
6402 .toggleClass( 'oo-ui-selectWidget-pressed', pressed
)
6403 .toggleClass( 'oo-ui-selectWidget-depressed', !pressed
);
6404 this.pressed
= pressed
;
6409 * Highlight an option. If the `item` param is omitted, no options will be highlighted
6410 * and any existing highlight will be removed. The highlight is mutually exclusive.
6412 * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight
6416 OO
.ui
.SelectWidget
.prototype.highlightItem = function ( item
) {
6417 var i
, len
, highlighted
,
6420 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6421 highlighted
= this.items
[ i
] === item
;
6422 if ( this.items
[ i
].isHighlighted() !== highlighted
) {
6423 this.items
[ i
].setHighlighted( highlighted
);
6429 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6431 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6433 this.emit( 'highlight', item
);
6440 * Fetch an item by its label.
6442 * @param {string} label Label of the item to select.
6443 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6444 * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists
6446 OO
.ui
.SelectWidget
.prototype.getItemFromLabel = function ( label
, prefix
) {
6448 len
= this.items
.length
,
6449 filter
= this.getItemMatcher( label
, true );
6451 for ( i
= 0; i
< len
; i
++ ) {
6452 item
= this.items
[ i
];
6453 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6460 filter
= this.getItemMatcher( label
, false );
6461 for ( i
= 0; i
< len
; i
++ ) {
6462 item
= this.items
[ i
];
6463 if ( item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() && filter( item
) ) {
6479 * Programmatically select an option by its label. If the item does not exist,
6480 * all options will be deselected.
6482 * @param {string} [label] Label of the item to select.
6483 * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches
6487 OO
.ui
.SelectWidget
.prototype.selectItemByLabel = function ( label
, prefix
) {
6488 var itemFromLabel
= this.getItemFromLabel( label
, !!prefix
);
6489 if ( label
=== undefined || !itemFromLabel
) {
6490 return this.selectItem();
6492 return this.selectItem( itemFromLabel
);
6496 * Programmatically select an option by its data. If the `data` parameter is omitted,
6497 * or if the item does not exist, all options will be deselected.
6499 * @param {Object|string} [data] Value of the item to select, omit to deselect all
6503 OO
.ui
.SelectWidget
.prototype.selectItemByData = function ( data
) {
6504 var itemFromData
= this.getItemFromData( data
);
6505 if ( data
=== undefined || !itemFromData
) {
6506 return this.selectItem();
6508 return this.selectItem( itemFromData
);
6512 * Programmatically select an option by its reference. If the `item` parameter is omitted,
6513 * all options will be deselected.
6515 * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all
6519 OO
.ui
.SelectWidget
.prototype.selectItem = function ( item
) {
6520 var i
, len
, selected
,
6523 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6524 selected
= this.items
[ i
] === item
;
6525 if ( this.items
[ i
].isSelected() !== selected
) {
6526 this.items
[ i
].setSelected( selected
);
6531 if ( item
&& !item
.constructor.static.highlightable
) {
6533 this.$focusOwner
.attr( 'aria-activedescendant', item
.getElementId() );
6535 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
6538 this.emit( 'select', item
);
6547 * Press is a state that occurs when a user mouses down on an item, but has not
6548 * yet let go of the mouse. The item may appear selected, but it will not be selected until the user
6549 * releases the mouse.
6551 * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all
6555 OO
.ui
.SelectWidget
.prototype.pressItem = function ( item
) {
6556 var i
, len
, pressed
,
6559 for ( i
= 0, len
= this.items
.length
; i
< len
; i
++ ) {
6560 pressed
= this.items
[ i
] === item
;
6561 if ( this.items
[ i
].isPressed() !== pressed
) {
6562 this.items
[ i
].setPressed( pressed
);
6567 this.emit( 'press', item
);
6576 * Note that ‘choose’ should never be modified programmatically. A user can choose
6577 * an option with the keyboard or mouse and it becomes selected. To select an item programmatically,
6578 * use the #selectItem method.
6580 * This method is identical to #selectItem, but may vary in subclasses that take additional action
6581 * when users choose an item with the keyboard or mouse.
6583 * @param {OO.ui.OptionWidget} item Item to choose
6587 OO
.ui
.SelectWidget
.prototype.chooseItem = function ( item
) {
6589 this.selectItem( item
);
6590 this.emit( 'choose', item
);
6597 * Get an option by its position relative to the specified item (or to the start of the option array,
6598 * if item is `null`). The direction in which to search through the option array is specified with a
6599 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
6600 * `null` if there are no options in the array.
6602 * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
6603 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
6604 * @param {Function} [filter] Only consider items for which this function returns
6605 * true. Function takes an OO.ui.OptionWidget and returns a boolean.
6606 * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select
6608 OO
.ui
.SelectWidget
.prototype.getRelativeSelectableItem = function ( item
, direction
, filter
) {
6609 var currentIndex
, nextIndex
, i
,
6610 increase
= direction
> 0 ? 1 : -1,
6611 len
= this.items
.length
;
6613 if ( item
instanceof OO
.ui
.OptionWidget
) {
6614 currentIndex
= this.items
.indexOf( item
);
6615 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
6617 // If no item is selected and moving forward, start at the beginning.
6618 // If moving backward, start at the end.
6619 nextIndex
= direction
> 0 ? 0 : len
- 1;
6622 for ( i
= 0; i
< len
; i
++ ) {
6623 item
= this.items
[ nextIndex
];
6625 item
instanceof OO
.ui
.OptionWidget
&& item
.isSelectable() &&
6626 ( !filter
|| filter( item
) )
6630 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
6636 * Get the next selectable item or `null` if there are no selectable items.
6637 * Disabled options and menu-section markers and breaks are not selectable.
6639 * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items
6641 OO
.ui
.SelectWidget
.prototype.getFirstSelectableItem = function () {
6642 return this.getRelativeSelectableItem( null, 1 );
6646 * Add an array of options to the select. Optionally, an index number can be used to
6647 * specify an insertion point.
6649 * @param {OO.ui.OptionWidget[]} items Items to add
6650 * @param {number} [index] Index to insert items after
6654 OO
.ui
.SelectWidget
.prototype.addItems = function ( items
, index
) {
6656 OO
.ui
.mixin
.GroupWidget
.prototype.addItems
.call( this, items
, index
);
6658 // Always provide an index, even if it was omitted
6659 this.emit( 'add', items
, index
=== undefined ? this.items
.length
- items
.length
- 1 : index
);
6665 * Remove the specified array of options from the select. Options will be detached
6666 * from the DOM, not removed, so they can be reused later. To remove all options from
6667 * the select, you may wish to use the #clearItems method instead.
6669 * @param {OO.ui.OptionWidget[]} items Items to remove
6673 OO
.ui
.SelectWidget
.prototype.removeItems = function ( items
) {
6676 // Deselect items being removed
6677 for ( i
= 0, len
= items
.length
; i
< len
; i
++ ) {
6679 if ( item
.isSelected() ) {
6680 this.selectItem( null );
6685 OO
.ui
.mixin
.GroupWidget
.prototype.removeItems
.call( this, items
);
6687 this.emit( 'remove', items
);
6693 * Clear all options from the select. Options will be detached from the DOM, not removed,
6694 * so that they can be reused later. To remove a subset of options from the select, use
6695 * the #removeItems method.
6700 OO
.ui
.SelectWidget
.prototype.clearItems = function () {
6701 var items
= this.items
.slice();
6704 OO
.ui
.mixin
.GroupWidget
.prototype.clearItems
.call( this );
6707 this.selectItem( null );
6709 this.emit( 'remove', items
);
6715 * Set the DOM element which has focus while the user is interacting with this SelectWidget.
6717 * Currently this is just used to set `aria-activedescendant` on it.
6720 * @param {jQuery} $focusOwner
6722 OO
.ui
.SelectWidget
.prototype.setFocusOwner = function ( $focusOwner
) {
6723 this.$focusOwner
= $focusOwner
;
6727 * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured
6728 * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}.
6729 * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive
6730 * options. For more information about options and selects, please see the
6731 * [OOjs UI documentation on MediaWiki][1].
6734 * // Decorated options in a select widget
6735 * var select = new OO.ui.SelectWidget( {
6737 * new OO.ui.DecoratedOptionWidget( {
6739 * label: 'Option with icon',
6742 * new OO.ui.DecoratedOptionWidget( {
6744 * label: 'Option with indicator',
6749 * $( 'body' ).append( select.$element );
6751 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6754 * @extends OO.ui.OptionWidget
6755 * @mixins OO.ui.mixin.IconElement
6756 * @mixins OO.ui.mixin.IndicatorElement
6759 * @param {Object} [config] Configuration options
6761 OO
.ui
.DecoratedOptionWidget
= function OoUiDecoratedOptionWidget( config
) {
6762 // Parent constructor
6763 OO
.ui
.DecoratedOptionWidget
.parent
.call( this, config
);
6765 // Mixin constructors
6766 OO
.ui
.mixin
.IconElement
.call( this, config
);
6767 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
6771 .addClass( 'oo-ui-decoratedOptionWidget' )
6772 .prepend( this.$icon
)
6773 .append( this.$indicator
);
6778 OO
.inheritClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.OptionWidget
);
6779 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IconElement
);
6780 OO
.mixinClass( OO
.ui
.DecoratedOptionWidget
, OO
.ui
.mixin
.IndicatorElement
);
6783 * MenuOptionWidget is an option widget that looks like a menu item. The class is used with
6784 * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see
6785 * the [OOjs UI documentation on MediaWiki] [1] for more information.
6787 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
6790 * @extends OO.ui.DecoratedOptionWidget
6793 * @param {Object} [config] Configuration options
6795 OO
.ui
.MenuOptionWidget
= function OoUiMenuOptionWidget( config
) {
6796 // Parent constructor
6797 OO
.ui
.MenuOptionWidget
.parent
.call( this, config
);
6800 this.$element
.addClass( 'oo-ui-menuOptionWidget' );
6805 OO
.inheritClass( OO
.ui
.MenuOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6807 /* Static Properties */
6813 OO
.ui
.MenuOptionWidget
.static.scrollIntoViewOnSelect
= true;
6816 * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related
6817 * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected.
6820 * var myDropdown = new OO.ui.DropdownWidget( {
6823 * new OO.ui.MenuSectionOptionWidget( {
6826 * new OO.ui.MenuOptionWidget( {
6828 * label: 'Welsh Corgi'
6830 * new OO.ui.MenuOptionWidget( {
6832 * label: 'Standard Poodle'
6834 * new OO.ui.MenuSectionOptionWidget( {
6837 * new OO.ui.MenuOptionWidget( {
6844 * $( 'body' ).append( myDropdown.$element );
6847 * @extends OO.ui.DecoratedOptionWidget
6850 * @param {Object} [config] Configuration options
6852 OO
.ui
.MenuSectionOptionWidget
= function OoUiMenuSectionOptionWidget( config
) {
6853 // Parent constructor
6854 OO
.ui
.MenuSectionOptionWidget
.parent
.call( this, config
);
6857 this.$element
.addClass( 'oo-ui-menuSectionOptionWidget' )
6858 .removeAttr( 'role aria-selected' );
6863 OO
.inheritClass( OO
.ui
.MenuSectionOptionWidget
, OO
.ui
.DecoratedOptionWidget
);
6865 /* Static Properties */
6871 OO
.ui
.MenuSectionOptionWidget
.static.selectable
= false;
6877 OO
.ui
.MenuSectionOptionWidget
.static.highlightable
= false;
6880 * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and
6881 * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget.
6882 * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget},
6883 * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus.
6884 * MenuSelectWidgets themselves are not instantiated directly, rather subclassed
6885 * and customized to be opened, closed, and displayed as needed.
6887 * By default, menus are clipped to the visible viewport and are not visible when a user presses the
6888 * mouse outside the menu.
6890 * Menus also have support for keyboard interaction:
6892 * - Enter/Return key: choose and select a menu option
6893 * - Up-arrow key: highlight the previous menu option
6894 * - Down-arrow key: highlight the next menu option
6895 * - Esc key: hide the menu
6897 * Unlike most widgets, MenuSelectWidget is initially hidden and must be shown by calling #toggle.
6899 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
6900 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
6903 * @extends OO.ui.SelectWidget
6904 * @mixins OO.ui.mixin.ClippableElement
6905 * @mixins OO.ui.mixin.FloatableElement
6908 * @param {Object} [config] Configuration options
6909 * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match
6910 * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}
6911 * and {@link OO.ui.mixin.LookupElement LookupElement}
6912 * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match
6913 * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget}
6914 * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse
6915 * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button
6916 * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks
6917 * that button, unless the button (or its parent widget) is passed in here.
6918 * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu.
6919 * @cfg {jQuery} [$autoCloseIgnore] If these elements are clicked, don't auto-hide the menu.
6920 * @cfg {boolean} [hideOnChoose=true] Hide the menu when the user chooses an option.
6921 * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input
6922 * @cfg {boolean} [highlightOnFilter] Highlight the first result when filtering
6923 * @cfg {number} [width] Width of the menu
6925 OO
.ui
.MenuSelectWidget
= function OoUiMenuSelectWidget( config
) {
6926 // Configuration initialization
6927 config
= config
|| {};
6929 // Parent constructor
6930 OO
.ui
.MenuSelectWidget
.parent
.call( this, config
);
6932 // Mixin constructors
6933 OO
.ui
.mixin
.ClippableElement
.call( this, $.extend( {}, config
, { $clippable
: this.$group
} ) );
6934 OO
.ui
.mixin
.FloatableElement
.call( this, config
);
6937 this.autoHide
= config
.autoHide
=== undefined || !!config
.autoHide
;
6938 this.hideOnChoose
= config
.hideOnChoose
=== undefined || !!config
.hideOnChoose
;
6939 this.filterFromInput
= !!config
.filterFromInput
;
6940 this.$input
= config
.$input
? config
.$input
: config
.input
? config
.input
.$input
: null;
6941 this.$widget
= config
.widget
? config
.widget
.$element
: null;
6942 this.$autoCloseIgnore
= config
.$autoCloseIgnore
|| $( [] );
6943 this.onDocumentMouseDownHandler
= this.onDocumentMouseDown
.bind( this );
6944 this.onInputEditHandler
= OO
.ui
.debounce( this.updateItemVisibility
.bind( this ), 100 );
6945 this.highlightOnFilter
= !!config
.highlightOnFilter
;
6946 this.width
= config
.width
;
6949 this.$element
.addClass( 'oo-ui-menuSelectWidget' );
6950 if ( config
.widget
) {
6951 this.setFocusOwner( config
.widget
.$tabIndexed
);
6954 // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
6955 // that reference properties not initialized at that time of parent class construction
6956 // TODO: Find a better way to handle post-constructor setup
6957 this.visible
= false;
6958 this.$element
.addClass( 'oo-ui-element-hidden' );
6963 OO
.inheritClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.SelectWidget
);
6964 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.ClippableElement
);
6965 OO
.mixinClass( OO
.ui
.MenuSelectWidget
, OO
.ui
.mixin
.FloatableElement
);
6972 * The menu is ready: it is visible and has been positioned and clipped.
6978 * Handles document mouse down events.
6981 * @param {MouseEvent} e Mouse down event
6983 OO
.ui
.MenuSelectWidget
.prototype.onDocumentMouseDown = function ( e
) {
6987 this.$element
.add( this.$widget
).add( this.$autoCloseIgnore
).get(),
6992 this.toggle( false );
6999 OO
.ui
.MenuSelectWidget
.prototype.onKeyDown = function ( e
) {
7000 var currentItem
= this.getHighlightedItem() || this.getSelectedItem();
7002 if ( !this.isDisabled() && this.isVisible() ) {
7003 switch ( e
.keyCode
) {
7004 case OO
.ui
.Keys
.LEFT
:
7005 case OO
.ui
.Keys
.RIGHT
:
7006 // Do nothing if a text field is associated, arrow keys will be handled natively
7007 if ( !this.$input
) {
7008 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
7011 case OO
.ui
.Keys
.ESCAPE
:
7012 case OO
.ui
.Keys
.TAB
:
7013 if ( currentItem
) {
7014 currentItem
.setHighlighted( false );
7016 this.toggle( false );
7017 // Don't prevent tabbing away, prevent defocusing
7018 if ( e
.keyCode
=== OO
.ui
.Keys
.ESCAPE
) {
7020 e
.stopPropagation();
7024 OO
.ui
.MenuSelectWidget
.parent
.prototype.onKeyDown
.call( this, e
);
7031 * Update menu item visibility after input changes.
7035 OO
.ui
.MenuSelectWidget
.prototype.updateItemVisibility = function () {
7036 var i
, item
, visible
, section
, sectionEmpty
,
7037 firstItemFound
= false,
7039 len
= this.items
.length
,
7040 showAll
= !this.isVisible(),
7041 filter
= showAll
? null : this.getItemMatcher( this.$input
.val() ),
7042 exactFilter
= this.getItemMatcher( this.$input
.val(), true ),
7045 // Hide non-matching options, and also hide section headers if all options
7046 // in their section are hidden.
7047 for ( i
= 0; i
< len
; i
++ ) {
7048 item
= this.items
[ i
];
7049 if ( item
instanceof OO
.ui
.MenuSectionOptionWidget
) {
7051 // If the previous section was empty, hide its header
7052 section
.toggle( showAll
|| !sectionEmpty
);
7055 sectionEmpty
= true;
7056 } else if ( item
instanceof OO
.ui
.OptionWidget
) {
7057 visible
= showAll
|| filter( item
);
7058 exactMatch
= exactMatch
|| exactFilter( item
);
7059 anyVisible
= anyVisible
|| visible
;
7060 sectionEmpty
= sectionEmpty
&& !visible
;
7061 item
.toggle( visible
);
7062 if ( this.highlightOnFilter
&& visible
&& !firstItemFound
) {
7063 // Highlight the first item in the list
7064 this.highlightItem( item
);
7065 firstItemFound
= true;
7069 // Process the final section
7071 section
.toggle( showAll
|| !sectionEmpty
);
7074 if ( anyVisible
&& this.items
.length
&& !exactMatch
) {
7075 this.scrollItemIntoView( this.items
[ 0 ] );
7078 this.$element
.toggleClass( 'oo-ui-menuSelectWidget-invisible', !anyVisible
);
7080 // Reevaluate clipping
7087 OO
.ui
.MenuSelectWidget
.prototype.bindKeyDownListener = function () {
7088 if ( this.$input
) {
7089 this.$input
.on( 'keydown', this.onKeyDownHandler
);
7091 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyDownListener
.call( this );
7098 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyDownListener = function () {
7099 if ( this.$input
) {
7100 this.$input
.off( 'keydown', this.onKeyDownHandler
);
7102 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyDownListener
.call( this );
7109 OO
.ui
.MenuSelectWidget
.prototype.bindKeyPressListener = function () {
7110 if ( this.$input
) {
7111 if ( this.filterFromInput
) {
7112 this.$input
.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7113 this.updateItemVisibility();
7116 OO
.ui
.MenuSelectWidget
.parent
.prototype.bindKeyPressListener
.call( this );
7123 OO
.ui
.MenuSelectWidget
.prototype.unbindKeyPressListener = function () {
7124 if ( this.$input
) {
7125 if ( this.filterFromInput
) {
7126 this.$input
.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler
);
7127 this.updateItemVisibility();
7130 OO
.ui
.MenuSelectWidget
.parent
.prototype.unbindKeyPressListener
.call( this );
7137 * When a user chooses an item, the menu is closed, unless the hideOnChoose config option is set to false.
7139 * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard
7140 * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method.
7142 * @param {OO.ui.OptionWidget} item Item to choose
7145 OO
.ui
.MenuSelectWidget
.prototype.chooseItem = function ( item
) {
7146 OO
.ui
.MenuSelectWidget
.parent
.prototype.chooseItem
.call( this, item
);
7147 if ( this.hideOnChoose
) {
7148 this.toggle( false );
7156 OO
.ui
.MenuSelectWidget
.prototype.addItems = function ( items
, index
) {
7158 OO
.ui
.MenuSelectWidget
.parent
.prototype.addItems
.call( this, items
, index
);
7160 // Reevaluate clipping
7169 OO
.ui
.MenuSelectWidget
.prototype.removeItems = function ( items
) {
7171 OO
.ui
.MenuSelectWidget
.parent
.prototype.removeItems
.call( this, items
);
7173 // Reevaluate clipping
7182 OO
.ui
.MenuSelectWidget
.prototype.clearItems = function () {
7184 OO
.ui
.MenuSelectWidget
.parent
.prototype.clearItems
.call( this );
7186 // Reevaluate clipping
7193 * Toggle visibility of the menu. The menu is initially hidden and must be shown by calling
7194 * `.toggle( true )` after its #$element is attached to the DOM.
7196 * Do not show the menu while it is not attached to the DOM. The calculations required to display
7197 * it in the right place and with the right dimensions only work correctly while it is attached.
7198 * Side-effects may include broken interface and exceptions being thrown. This wasn't always
7199 * strictly enforced, so currently it only generates a warning in the browser console.
7204 OO
.ui
.MenuSelectWidget
.prototype.toggle = function ( visible
) {
7207 visible
= ( visible
=== undefined ? !this.visible
: !!visible
) && !!this.items
.length
;
7208 change
= visible
!== this.isVisible();
7210 if ( visible
&& !this.warnedUnattached
&& !this.isElementAttached() ) {
7211 OO
.ui
.warnDeprecation( 'MenuSelectWidget#toggle: Before calling this method, the menu must be attached to the DOM.' );
7212 this.warnedUnattached
= true;
7215 if ( change
&& visible
&& ( this.width
|| this.$floatableContainer
) ) {
7216 this.setIdealSize( this.width
|| this.$floatableContainer
.width() );
7220 OO
.ui
.MenuSelectWidget
.parent
.prototype.toggle
.call( this, visible
);
7224 this.bindKeyDownListener();
7225 this.bindKeyPressListener();
7227 this.togglePositioning( !!this.$floatableContainer
);
7228 this.toggleClipping( true );
7230 if ( this.getSelectedItem() ) {
7231 this.$focusOwner
.attr( 'aria-activedescendant', this.getSelectedItem().getElementId() );
7232 this.getSelectedItem().scrollElementIntoView( { duration
: 0 } );
7236 if ( this.autoHide
) {
7237 this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7240 this.emit( 'ready' );
7242 this.$focusOwner
.removeAttr( 'aria-activedescendant' );
7243 this.unbindKeyDownListener();
7244 this.unbindKeyPressListener();
7245 this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler
, true );
7246 this.togglePositioning( false );
7247 this.toggleClipping( false );
7255 * DropdownWidgets are not menus themselves, rather they contain a menu of options created with
7256 * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that
7257 * users can interact with it.
7259 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7260 * OO.ui.DropdownInputWidget instead.
7263 * // Example: A DropdownWidget with a menu that contains three options
7264 * var dropDown = new OO.ui.DropdownWidget( {
7265 * label: 'Dropdown menu: Select a menu option',
7268 * new OO.ui.MenuOptionWidget( {
7272 * new OO.ui.MenuOptionWidget( {
7276 * new OO.ui.MenuOptionWidget( {
7284 * $( 'body' ).append( dropDown.$element );
7286 * dropDown.getMenu().selectItemByData( 'b' );
7288 * dropDown.getMenu().getSelectedItem().getData(); // returns 'b'
7290 * For more information, please see the [OOjs UI documentation on MediaWiki] [1].
7292 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7295 * @extends OO.ui.Widget
7296 * @mixins OO.ui.mixin.IconElement
7297 * @mixins OO.ui.mixin.IndicatorElement
7298 * @mixins OO.ui.mixin.LabelElement
7299 * @mixins OO.ui.mixin.TitledElement
7300 * @mixins OO.ui.mixin.TabIndexedElement
7303 * @param {Object} [config] Configuration options
7304 * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.MenuSelectWidget menu select widget}
7305 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
7306 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
7307 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
7308 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
7310 OO
.ui
.DropdownWidget
= function OoUiDropdownWidget( config
) {
7311 // Configuration initialization
7312 config
= $.extend( { indicator
: 'down' }, config
);
7314 // Parent constructor
7315 OO
.ui
.DropdownWidget
.parent
.call( this, config
);
7317 // Properties (must be set before TabIndexedElement constructor call)
7318 this.$handle
= this.$( '<span>' );
7319 this.$overlay
= config
.$overlay
|| this.$element
;
7321 // Mixin constructors
7322 OO
.ui
.mixin
.IconElement
.call( this, config
);
7323 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
7324 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7325 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
7326 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$handle
} ) );
7329 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend( {
7331 $floatableContainer
: this.$element
7336 click
: this.onClick
.bind( this ),
7337 keydown
: this.onKeyDown
.bind( this ),
7338 // Hack? Handle type-to-search when menu is not expanded and not handling its own events
7339 keypress
: this.menu
.onKeyPressHandler
,
7340 blur
: this.menu
.clearKeyPressBuffer
.bind( this.menu
)
7342 this.menu
.connect( this, {
7343 select
: 'onMenuSelect',
7344 toggle
: 'onMenuToggle'
7349 .addClass( 'oo-ui-dropdownWidget-handle' )
7352 'aria-owns': this.menu
.getElementId(),
7353 'aria-autocomplete': 'list'
7355 .append( this.$icon
, this.$label
, this.$indicator
);
7357 .addClass( 'oo-ui-dropdownWidget' )
7358 .append( this.$handle
);
7359 this.$overlay
.append( this.menu
.$element
);
7364 OO
.inheritClass( OO
.ui
.DropdownWidget
, OO
.ui
.Widget
);
7365 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IconElement
);
7366 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.IndicatorElement
);
7367 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.LabelElement
);
7368 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TitledElement
);
7369 OO
.mixinClass( OO
.ui
.DropdownWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7376 * @return {OO.ui.MenuSelectWidget} Menu of widget
7378 OO
.ui
.DropdownWidget
.prototype.getMenu = function () {
7383 * Handles menu select events.
7386 * @param {OO.ui.MenuOptionWidget} item Selected menu item
7388 OO
.ui
.DropdownWidget
.prototype.onMenuSelect = function ( item
) {
7392 this.setLabel( null );
7396 selectedLabel
= item
.getLabel();
7398 // If the label is a DOM element, clone it, because setLabel will append() it
7399 if ( selectedLabel
instanceof jQuery
) {
7400 selectedLabel
= selectedLabel
.clone();
7403 this.setLabel( selectedLabel
);
7407 * Handle menu toggle events.
7410 * @param {boolean} isVisible Menu toggle event
7412 OO
.ui
.DropdownWidget
.prototype.onMenuToggle = function ( isVisible
) {
7413 this.$element
.toggleClass( 'oo-ui-dropdownWidget-open', isVisible
);
7417 * Handle mouse click events.
7420 * @param {jQuery.Event} e Mouse click event
7422 OO
.ui
.DropdownWidget
.prototype.onClick = function ( e
) {
7423 if ( !this.isDisabled() && e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
7430 * Handle key down events.
7433 * @param {jQuery.Event} e Key down event
7435 OO
.ui
.DropdownWidget
.prototype.onKeyDown = function ( e
) {
7437 !this.isDisabled() &&
7439 e
.which
=== OO
.ui
.Keys
.ENTER
||
7441 !this.menu
.isVisible() &&
7443 e
.which
=== OO
.ui
.Keys
.SPACE
||
7444 e
.which
=== OO
.ui
.Keys
.UP
||
7445 e
.which
=== OO
.ui
.Keys
.DOWN
7456 * RadioOptionWidget is an option widget that looks like a radio button.
7457 * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options.
7458 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7460 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7463 * @extends OO.ui.OptionWidget
7466 * @param {Object} [config] Configuration options
7468 OO
.ui
.RadioOptionWidget
= function OoUiRadioOptionWidget( config
) {
7469 // Configuration initialization
7470 config
= config
|| {};
7472 // Properties (must be done before parent constructor which calls #setDisabled)
7473 this.radio
= new OO
.ui
.RadioInputWidget( { value
: config
.data
, tabIndex
: -1 } );
7475 // Parent constructor
7476 OO
.ui
.RadioOptionWidget
.parent
.call( this, config
);
7479 // Remove implicit role, we're handling it ourselves
7480 this.radio
.$input
.attr( 'role', 'presentation' );
7482 .addClass( 'oo-ui-radioOptionWidget' )
7483 .attr( 'role', 'radio' )
7484 .attr( 'aria-checked', 'false' )
7485 .removeAttr( 'aria-selected' )
7486 .prepend( this.radio
.$element
);
7491 OO
.inheritClass( OO
.ui
.RadioOptionWidget
, OO
.ui
.OptionWidget
);
7493 /* Static Properties */
7499 OO
.ui
.RadioOptionWidget
.static.highlightable
= false;
7505 OO
.ui
.RadioOptionWidget
.static.scrollIntoViewOnSelect
= true;
7511 OO
.ui
.RadioOptionWidget
.static.pressable
= false;
7517 OO
.ui
.RadioOptionWidget
.static.tagName
= 'label';
7524 OO
.ui
.RadioOptionWidget
.prototype.setSelected = function ( state
) {
7525 OO
.ui
.RadioOptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7527 this.radio
.setSelected( state
);
7529 .attr( 'aria-checked', state
.toString() )
7530 .removeAttr( 'aria-selected' );
7538 OO
.ui
.RadioOptionWidget
.prototype.setDisabled = function ( disabled
) {
7539 OO
.ui
.RadioOptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7541 this.radio
.setDisabled( this.isDisabled() );
7547 * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio
7548 * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides
7549 * an interface for adding, removing and selecting options.
7550 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7552 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7553 * OO.ui.RadioSelectInputWidget instead.
7556 * // A RadioSelectWidget with RadioOptions.
7557 * var option1 = new OO.ui.RadioOptionWidget( {
7559 * label: 'Selected radio option'
7562 * var option2 = new OO.ui.RadioOptionWidget( {
7564 * label: 'Unselected radio option'
7567 * var radioSelect=new OO.ui.RadioSelectWidget( {
7568 * items: [ option1, option2 ]
7571 * // Select 'option 1' using the RadioSelectWidget's selectItem() method.
7572 * radioSelect.selectItem( option1 );
7574 * $( 'body' ).append( radioSelect.$element );
7576 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7580 * @extends OO.ui.SelectWidget
7581 * @mixins OO.ui.mixin.TabIndexedElement
7584 * @param {Object} [config] Configuration options
7586 OO
.ui
.RadioSelectWidget
= function OoUiRadioSelectWidget( config
) {
7587 // Parent constructor
7588 OO
.ui
.RadioSelectWidget
.parent
.call( this, config
);
7590 // Mixin constructors
7591 OO
.ui
.mixin
.TabIndexedElement
.call( this, config
);
7595 focus
: this.bindKeyDownListener
.bind( this ),
7596 blur
: this.unbindKeyDownListener
.bind( this )
7601 .addClass( 'oo-ui-radioSelectWidget' )
7602 .attr( 'role', 'radiogroup' );
7607 OO
.inheritClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.SelectWidget
);
7608 OO
.mixinClass( OO
.ui
.RadioSelectWidget
, OO
.ui
.mixin
.TabIndexedElement
);
7611 * MultioptionWidgets are special elements that can be selected and configured with data. The
7612 * data is often unique for each option, but it does not have to be. MultioptionWidgets are used
7613 * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information
7614 * and examples, please see the [OOjs UI documentation on MediaWiki][1].
7616 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions
7619 * @extends OO.ui.Widget
7620 * @mixins OO.ui.mixin.ItemWidget
7621 * @mixins OO.ui.mixin.LabelElement
7624 * @param {Object} [config] Configuration options
7625 * @cfg {boolean} [selected=false] Whether the option is initially selected
7627 OO
.ui
.MultioptionWidget
= function OoUiMultioptionWidget( config
) {
7628 // Configuration initialization
7629 config
= config
|| {};
7631 // Parent constructor
7632 OO
.ui
.MultioptionWidget
.parent
.call( this, config
);
7634 // Mixin constructors
7635 OO
.ui
.mixin
.ItemWidget
.call( this );
7636 OO
.ui
.mixin
.LabelElement
.call( this, config
);
7639 this.selected
= null;
7643 .addClass( 'oo-ui-multioptionWidget' )
7644 .append( this.$label
);
7645 this.setSelected( config
.selected
);
7650 OO
.inheritClass( OO
.ui
.MultioptionWidget
, OO
.ui
.Widget
);
7651 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.ItemWidget
);
7652 OO
.mixinClass( OO
.ui
.MultioptionWidget
, OO
.ui
.mixin
.LabelElement
);
7659 * A change event is emitted when the selected state of the option changes.
7661 * @param {boolean} selected Whether the option is now selected
7667 * Check if the option is selected.
7669 * @return {boolean} Item is selected
7671 OO
.ui
.MultioptionWidget
.prototype.isSelected = function () {
7672 return this.selected
;
7676 * Set the option’s selected state. In general, all modifications to the selection
7677 * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )}
7678 * method instead of this method.
7680 * @param {boolean} [state=false] Select option
7683 OO
.ui
.MultioptionWidget
.prototype.setSelected = function ( state
) {
7685 if ( this.selected
!== state
) {
7686 this.selected
= state
;
7687 this.emit( 'change', state
);
7688 this.$element
.toggleClass( 'oo-ui-multioptionWidget-selected', state
);
7694 * MultiselectWidget allows selecting multiple options from a list.
7696 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
7698 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
7702 * @extends OO.ui.Widget
7703 * @mixins OO.ui.mixin.GroupWidget
7706 * @param {Object} [config] Configuration options
7707 * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect.
7709 OO
.ui
.MultiselectWidget
= function OoUiMultiselectWidget( config
) {
7710 // Parent constructor
7711 OO
.ui
.MultiselectWidget
.parent
.call( this, config
);
7713 // Configuration initialization
7714 config
= config
|| {};
7716 // Mixin constructors
7717 OO
.ui
.mixin
.GroupWidget
.call( this, config
);
7720 this.aggregate( { change
: 'select' } );
7721 // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted
7722 // by GroupElement only when items are added/removed
7723 this.connect( this, { select
: [ 'emit', 'change' ] } );
7726 if ( config
.items
) {
7727 this.addItems( config
.items
);
7729 this.$group
.addClass( 'oo-ui-multiselectWidget-group' );
7730 this.$element
.addClass( 'oo-ui-multiselectWidget' )
7731 .append( this.$group
);
7736 OO
.inheritClass( OO
.ui
.MultiselectWidget
, OO
.ui
.Widget
);
7737 OO
.mixinClass( OO
.ui
.MultiselectWidget
, OO
.ui
.mixin
.GroupWidget
);
7744 * A change event is emitted when the set of items changes, or an item is selected or deselected.
7750 * A select event is emitted when an item is selected or deselected.
7756 * Get options that are selected.
7758 * @return {OO.ui.MultioptionWidget[]} Selected options
7760 OO
.ui
.MultiselectWidget
.prototype.getSelectedItems = function () {
7761 return this.items
.filter( function ( item
) {
7762 return item
.isSelected();
7767 * Get the data of options that are selected.
7769 * @return {Object[]|string[]} Values of selected options
7771 OO
.ui
.MultiselectWidget
.prototype.getSelectedItemsData = function () {
7772 return this.getSelectedItems().map( function ( item
) {
7778 * Select options by reference. Options not mentioned in the `items` array will be deselected.
7780 * @param {OO.ui.MultioptionWidget[]} items Items to select
7783 OO
.ui
.MultiselectWidget
.prototype.selectItems = function ( items
) {
7784 this.items
.forEach( function ( item
) {
7785 var selected
= items
.indexOf( item
) !== -1;
7786 item
.setSelected( selected
);
7792 * Select items by their data. Options not mentioned in the `datas` array will be deselected.
7794 * @param {Object[]|string[]} datas Values of items to select
7797 OO
.ui
.MultiselectWidget
.prototype.selectItemsByData = function ( datas
) {
7800 items
= datas
.map( function ( data
) {
7801 return widget
.getItemFromData( data
);
7803 this.selectItems( items
);
7808 * CheckboxMultioptionWidget is an option widget that looks like a checkbox.
7809 * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options.
7810 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information.
7812 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option
7815 * @extends OO.ui.MultioptionWidget
7818 * @param {Object} [config] Configuration options
7820 OO
.ui
.CheckboxMultioptionWidget
= function OoUiCheckboxMultioptionWidget( config
) {
7821 // Configuration initialization
7822 config
= config
|| {};
7824 // Properties (must be done before parent constructor which calls #setDisabled)
7825 this.checkbox
= new OO
.ui
.CheckboxInputWidget();
7827 // Parent constructor
7828 OO
.ui
.CheckboxMultioptionWidget
.parent
.call( this, config
);
7831 this.checkbox
.on( 'change', this.onCheckboxChange
.bind( this ) );
7832 this.$element
.on( 'keydown', this.onKeyDown
.bind( this ) );
7836 .addClass( 'oo-ui-checkboxMultioptionWidget' )
7837 .prepend( this.checkbox
.$element
);
7842 OO
.inheritClass( OO
.ui
.CheckboxMultioptionWidget
, OO
.ui
.MultioptionWidget
);
7844 /* Static Properties */
7850 OO
.ui
.CheckboxMultioptionWidget
.static.tagName
= 'label';
7855 * Handle checkbox selected state change.
7859 OO
.ui
.CheckboxMultioptionWidget
.prototype.onCheckboxChange = function () {
7860 this.setSelected( this.checkbox
.isSelected() );
7866 OO
.ui
.CheckboxMultioptionWidget
.prototype.setSelected = function ( state
) {
7867 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setSelected
.call( this, state
);
7868 this.checkbox
.setSelected( state
);
7875 OO
.ui
.CheckboxMultioptionWidget
.prototype.setDisabled = function ( disabled
) {
7876 OO
.ui
.CheckboxMultioptionWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
7877 this.checkbox
.setDisabled( this.isDisabled() );
7884 OO
.ui
.CheckboxMultioptionWidget
.prototype.focus = function () {
7885 this.checkbox
.focus();
7889 * Handle key down events.
7892 * @param {jQuery.Event} e
7894 OO
.ui
.CheckboxMultioptionWidget
.prototype.onKeyDown = function ( e
) {
7896 element
= this.getElementGroup(),
7899 if ( e
.keyCode
=== OO
.ui
.Keys
.LEFT
|| e
.keyCode
=== OO
.ui
.Keys
.UP
) {
7900 nextItem
= element
.getRelativeFocusableItem( this, -1 );
7901 } else if ( e
.keyCode
=== OO
.ui
.Keys
.RIGHT
|| e
.keyCode
=== OO
.ui
.Keys
.DOWN
) {
7902 nextItem
= element
.getRelativeFocusableItem( this, 1 );
7912 * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains
7913 * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The
7914 * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options.
7915 * Please see the [OOjs UI documentation on MediaWiki][1] for more information.
7917 * If you want to use this within an HTML form, such as a OO.ui.FormLayout, use
7918 * OO.ui.CheckboxMultiselectInputWidget instead.
7921 * // A CheckboxMultiselectWidget with CheckboxMultioptions.
7922 * var option1 = new OO.ui.CheckboxMultioptionWidget( {
7925 * label: 'Selected checkbox'
7928 * var option2 = new OO.ui.CheckboxMultioptionWidget( {
7930 * label: 'Unselected checkbox'
7933 * var multiselect=new OO.ui.CheckboxMultiselectWidget( {
7934 * items: [ option1, option2 ]
7937 * $( 'body' ).append( multiselect.$element );
7939 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options
7942 * @extends OO.ui.MultiselectWidget
7945 * @param {Object} [config] Configuration options
7947 OO
.ui
.CheckboxMultiselectWidget
= function OoUiCheckboxMultiselectWidget( config
) {
7948 // Parent constructor
7949 OO
.ui
.CheckboxMultiselectWidget
.parent
.call( this, config
);
7952 this.$lastClicked
= null;
7955 this.$group
.on( 'click', this.onClick
.bind( this ) );
7959 .addClass( 'oo-ui-checkboxMultiselectWidget' );
7964 OO
.inheritClass( OO
.ui
.CheckboxMultiselectWidget
, OO
.ui
.MultiselectWidget
);
7969 * Get an option by its position relative to the specified item (or to the start of the option array,
7970 * if item is `null`). The direction in which to search through the option array is specified with a
7971 * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or
7972 * `null` if there are no options in the array.
7974 * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array.
7975 * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward
7976 * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select
7978 OO
.ui
.CheckboxMultiselectWidget
.prototype.getRelativeFocusableItem = function ( item
, direction
) {
7979 var currentIndex
, nextIndex
, i
,
7980 increase
= direction
> 0 ? 1 : -1,
7981 len
= this.items
.length
;
7984 currentIndex
= this.items
.indexOf( item
);
7985 nextIndex
= ( currentIndex
+ increase
+ len
) % len
;
7987 // If no item is selected and moving forward, start at the beginning.
7988 // If moving backward, start at the end.
7989 nextIndex
= direction
> 0 ? 0 : len
- 1;
7992 for ( i
= 0; i
< len
; i
++ ) {
7993 item
= this.items
[ nextIndex
];
7994 if ( item
&& !item
.isDisabled() ) {
7997 nextIndex
= ( nextIndex
+ increase
+ len
) % len
;
8003 * Handle click events on checkboxes.
8005 * @param {jQuery.Event} e
8007 OO
.ui
.CheckboxMultiselectWidget
.prototype.onClick = function ( e
) {
8008 var $options
, lastClickedIndex
, nowClickedIndex
, i
, direction
, wasSelected
, items
,
8009 $lastClicked
= this.$lastClicked
,
8010 $nowClicked
= $( e
.target
).closest( '.oo-ui-checkboxMultioptionWidget' )
8011 .not( '.oo-ui-widget-disabled' );
8013 // Allow selecting multiple options at once by Shift-clicking them
8014 if ( $lastClicked
&& $nowClicked
.length
&& e
.shiftKey
) {
8015 $options
= this.$group
.find( '.oo-ui-checkboxMultioptionWidget' );
8016 lastClickedIndex
= $options
.index( $lastClicked
);
8017 nowClickedIndex
= $options
.index( $nowClicked
);
8018 // If it's the same item, either the user is being silly, or it's a fake event generated by the
8019 // browser. In either case we don't need custom handling.
8020 if ( nowClickedIndex
!== lastClickedIndex
) {
8022 wasSelected
= items
[ nowClickedIndex
].isSelected();
8023 direction
= nowClickedIndex
> lastClickedIndex
? 1 : -1;
8025 // This depends on the DOM order of the items and the order of the .items array being the same.
8026 for ( i
= lastClickedIndex
; i
!== nowClickedIndex
; i
+= direction
) {
8027 if ( !items
[ i
].isDisabled() ) {
8028 items
[ i
].setSelected( !wasSelected
);
8031 // For the now-clicked element, use immediate timeout to allow the browser to do its own
8032 // handling first, then set our value. The order in which events happen is different for
8033 // clicks on the <input> and on the <label> and there are additional fake clicks fired for
8034 // non-click actions that change the checkboxes.
8036 setTimeout( function () {
8037 if ( !items
[ nowClickedIndex
].isDisabled() ) {
8038 items
[ nowClickedIndex
].setSelected( !wasSelected
);
8044 if ( $nowClicked
.length
) {
8045 this.$lastClicked
= $nowClicked
;
8054 OO
.ui
.CheckboxMultiselectWidget
.prototype.focus = function () {
8056 if ( !this.isDisabled() ) {
8057 item
= this.getRelativeFocusableItem( null, 1 );
8068 OO
.ui
.CheckboxMultiselectWidget
.prototype.simulateLabelClick = function () {
8073 * FloatingMenuSelectWidget was a menu that would stick under a specified
8074 * container, even when it is inserted elsewhere in the document.
8075 * This functionality is now included in MenuSelectWidget, and FloatingMenuSelectWidget
8076 * is preserved for backwards-compatibility.
8079 * @extends OO.ui.MenuSelectWidget
8080 * @deprecated since v0.21.3, use MenuSelectWidget instead.
8083 * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for.
8084 * Deprecated, omit this parameter and specify `$container` instead.
8085 * @param {Object} [config] Configuration options
8086 * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under
8088 OO
.ui
.FloatingMenuSelectWidget
= function OoUiFloatingMenuSelectWidget( inputWidget
, config
) {
8089 OO
.ui
.warnDeprecation( 'FloatingMenuSelectWidget is deprecated. Use the MenuSelectWidget instead.' );
8091 // Allow 'inputWidget' parameter and config for backwards compatibility
8092 if ( OO
.isPlainObject( inputWidget
) && config
=== undefined ) {
8093 config
= inputWidget
;
8094 inputWidget
= config
.inputWidget
;
8097 // Configuration initialization
8098 config
= config
|| {};
8101 this.inputWidget
= inputWidget
; // For backwards compatibility
8102 this.$container
= config
.$floatableContainer
|| config
.$container
|| this.inputWidget
.$element
;
8104 // Parent constructor
8105 OO
.ui
.FloatingMenuSelectWidget
.parent
.call( this, $.extend( {}, config
, { $floatableContainer
: this.$container
} ) );
8108 this.$element
.addClass( 'oo-ui-floatingMenuSelectWidget' );
8109 // For backwards compatibility
8110 this.$element
.addClass( 'oo-ui-textInputMenuSelectWidget' );
8115 OO
.inheritClass( OO
.ui
.FloatingMenuSelectWidget
, OO
.ui
.MenuSelectWidget
);
8118 * Progress bars visually display the status of an operation, such as a download,
8119 * and can be either determinate or indeterminate:
8121 * - **determinate** process bars show the percent of an operation that is complete.
8123 * - **indeterminate** process bars use a visual display of motion to indicate that an operation
8124 * is taking place. Because the extent of an indeterminate operation is unknown, the bar does
8125 * not use percentages.
8127 * The value of the `progress` configuration determines whether the bar is determinate or indeterminate.
8130 * // Examples of determinate and indeterminate progress bars.
8131 * var progressBar1 = new OO.ui.ProgressBarWidget( {
8134 * var progressBar2 = new OO.ui.ProgressBarWidget();
8136 * // Create a FieldsetLayout to layout progress bars
8137 * var fieldset = new OO.ui.FieldsetLayout;
8138 * fieldset.addItems( [
8139 * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}),
8140 * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'})
8142 * $( 'body' ).append( fieldset.$element );
8145 * @extends OO.ui.Widget
8148 * @param {Object} [config] Configuration options
8149 * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate).
8150 * To create a determinate progress bar, specify a number that reflects the initial percent complete.
8151 * By default, the progress bar is indeterminate.
8153 OO
.ui
.ProgressBarWidget
= function OoUiProgressBarWidget( config
) {
8154 // Configuration initialization
8155 config
= config
|| {};
8157 // Parent constructor
8158 OO
.ui
.ProgressBarWidget
.parent
.call( this, config
);
8161 this.$bar
= $( '<div>' );
8162 this.progress
= null;
8165 this.setProgress( config
.progress
!== undefined ? config
.progress
: false );
8166 this.$bar
.addClass( 'oo-ui-progressBarWidget-bar' );
8169 role
: 'progressbar',
8171 'aria-valuemax': 100
8173 .addClass( 'oo-ui-progressBarWidget' )
8174 .append( this.$bar
);
8179 OO
.inheritClass( OO
.ui
.ProgressBarWidget
, OO
.ui
.Widget
);
8181 /* Static Properties */
8187 OO
.ui
.ProgressBarWidget
.static.tagName
= 'div';
8192 * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`.
8194 * @return {number|boolean} Progress percent
8196 OO
.ui
.ProgressBarWidget
.prototype.getProgress = function () {
8197 return this.progress
;
8201 * Set the percent of the process completed or `false` for an indeterminate process.
8203 * @param {number|boolean} progress Progress percent or `false` for indeterminate
8205 OO
.ui
.ProgressBarWidget
.prototype.setProgress = function ( progress
) {
8206 this.progress
= progress
;
8208 if ( progress
!== false ) {
8209 this.$bar
.css( 'width', this.progress
+ '%' );
8210 this.$element
.attr( 'aria-valuenow', this.progress
);
8212 this.$bar
.css( 'width', '' );
8213 this.$element
.removeAttr( 'aria-valuenow' );
8215 this.$element
.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress
=== false );
8219 * InputWidget is the base class for all input widgets, which
8220 * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs},
8221 * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}.
8222 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
8224 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8228 * @extends OO.ui.Widget
8229 * @mixins OO.ui.mixin.FlaggedElement
8230 * @mixins OO.ui.mixin.TabIndexedElement
8231 * @mixins OO.ui.mixin.TitledElement
8232 * @mixins OO.ui.mixin.AccessKeyedElement
8235 * @param {Object} [config] Configuration options
8236 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8237 * @cfg {string} [value=''] The value of the input.
8238 * @cfg {string} [dir] The directionality of the input (ltr/rtl).
8239 * @cfg {string} [inputId] The value of the input’s HTML `id` attribute.
8240 * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input
8241 * before it is accepted.
8243 OO
.ui
.InputWidget
= function OoUiInputWidget( config
) {
8244 // Configuration initialization
8245 config
= config
|| {};
8247 // Parent constructor
8248 OO
.ui
.InputWidget
.parent
.call( this, config
);
8251 // See #reusePreInfuseDOM about config.$input
8252 this.$input
= config
.$input
|| this.getInputElement( config
);
8254 this.inputFilter
= config
.inputFilter
;
8256 // Mixin constructors
8257 OO
.ui
.mixin
.FlaggedElement
.call( this, config
);
8258 OO
.ui
.mixin
.TabIndexedElement
.call( this, $.extend( {}, config
, { $tabIndexed
: this.$input
} ) );
8259 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8260 OO
.ui
.mixin
.AccessKeyedElement
.call( this, $.extend( {}, config
, { $accessKeyed
: this.$input
} ) );
8263 this.$input
.on( 'keydown mouseup cut paste change input select', this.onEdit
.bind( this ) );
8267 .addClass( 'oo-ui-inputWidget-input' )
8268 .attr( 'name', config
.name
)
8269 .prop( 'disabled', this.isDisabled() );
8271 .addClass( 'oo-ui-inputWidget' )
8272 .append( this.$input
);
8273 this.setValue( config
.value
);
8275 this.setDir( config
.dir
);
8277 if ( config
.inputId
!== undefined ) {
8278 this.setInputId( config
.inputId
);
8284 OO
.inheritClass( OO
.ui
.InputWidget
, OO
.ui
.Widget
);
8285 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.FlaggedElement
);
8286 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TabIndexedElement
);
8287 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.TitledElement
);
8288 OO
.mixinClass( OO
.ui
.InputWidget
, OO
.ui
.mixin
.AccessKeyedElement
);
8290 /* Static Methods */
8295 OO
.ui
.InputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
8296 config
= OO
.ui
.InputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
8297 // Reusing $input lets browsers preserve inputted values across page reloads (T114134)
8298 config
.$input
= $( node
).find( '.oo-ui-inputWidget-input' );
8305 OO
.ui
.InputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8306 var state
= OO
.ui
.InputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8307 if ( config
.$input
&& config
.$input
.length
) {
8308 state
.value
= config
.$input
.val();
8309 // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward
8310 state
.focus
= config
.$input
.is( ':focus' );
8320 * A change event is emitted when the value of the input changes.
8322 * @param {string} value
8328 * Get input element.
8330 * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in
8331 * different circumstances. The element must have a `value` property (like form elements).
8334 * @param {Object} config Configuration options
8335 * @return {jQuery} Input element
8337 OO
.ui
.InputWidget
.prototype.getInputElement = function () {
8338 return $( '<input>' );
8342 * Handle potentially value-changing events.
8345 * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event
8347 OO
.ui
.InputWidget
.prototype.onEdit = function () {
8349 if ( !this.isDisabled() ) {
8350 // Allow the stack to clear so the value will be updated
8351 setTimeout( function () {
8352 widget
.setValue( widget
.$input
.val() );
8358 * Get the value of the input.
8360 * @return {string} Input value
8362 OO
.ui
.InputWidget
.prototype.getValue = function () {
8363 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8364 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8365 var value
= this.$input
.val();
8366 if ( this.value
!== value
) {
8367 this.setValue( value
);
8373 * Set the directionality of the input.
8375 * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto'
8378 OO
.ui
.InputWidget
.prototype.setDir = function ( dir
) {
8379 this.$input
.prop( 'dir', dir
);
8384 * Set the value of the input.
8386 * @param {string} value New value
8390 OO
.ui
.InputWidget
.prototype.setValue = function ( value
) {
8391 value
= this.cleanUpValue( value
);
8392 // Update the DOM if it has changed. Note that with cleanUpValue, it
8393 // is possible for the DOM value to change without this.value changing.
8394 if ( this.$input
.val() !== value
) {
8395 this.$input
.val( value
);
8397 if ( this.value
!== value
) {
8399 this.emit( 'change', this.value
);
8405 * Clean up incoming value.
8407 * Ensures value is a string, and converts undefined and null to empty string.
8410 * @param {string} value Original value
8411 * @return {string} Cleaned up value
8413 OO
.ui
.InputWidget
.prototype.cleanUpValue = function ( value
) {
8414 if ( value
=== undefined || value
=== null ) {
8416 } else if ( this.inputFilter
) {
8417 return this.inputFilter( String( value
) );
8419 return String( value
);
8426 OO
.ui
.InputWidget
.prototype.setDisabled = function ( state
) {
8427 OO
.ui
.InputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8428 if ( this.$input
) {
8429 this.$input
.prop( 'disabled', this.isDisabled() );
8435 * Set the 'id' attribute of the `<input>` element.
8437 * @param {string} id
8440 OO
.ui
.InputWidget
.prototype.setInputId = function ( id
) {
8441 this.$input
.attr( 'id', id
);
8448 OO
.ui
.InputWidget
.prototype.restorePreInfuseState = function ( state
) {
8449 OO
.ui
.InputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8450 if ( state
.value
!== undefined && state
.value
!== this.getValue() ) {
8451 this.setValue( state
.value
);
8453 if ( state
.focus
) {
8459 * Data widget intended for creating 'hidden'-type inputs.
8462 * @extends OO.ui.Widget
8465 * @param {Object} [config] Configuration options
8466 * @cfg {string} [value=''] The value of the input.
8467 * @cfg {string} [name=''] The value of the input’s HTML `name` attribute.
8469 OO
.ui
.HiddenInputWidget
= function OoUiHiddenInputWidget( config
) {
8470 // Configuration initialization
8471 config
= $.extend( { value
: '', name
: '' }, config
);
8473 // Parent constructor
8474 OO
.ui
.HiddenInputWidget
.parent
.call( this, config
);
8477 this.$element
.attr( {
8479 value
: config
.value
,
8482 this.$element
.removeAttr( 'aria-disabled' );
8487 OO
.inheritClass( OO
.ui
.HiddenInputWidget
, OO
.ui
.Widget
);
8489 /* Static Properties */
8495 OO
.ui
.HiddenInputWidget
.static.tagName
= 'input';
8498 * ButtonInputWidget is used to submit HTML forms and is intended to be used within
8499 * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably
8500 * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an
8501 * HTML `<button>` (the default) or an HTML `<input>` tags. See the
8502 * [OOjs UI documentation on MediaWiki] [1] for more information.
8505 * // A ButtonInputWidget rendered as an HTML button, the default.
8506 * var button = new OO.ui.ButtonInputWidget( {
8507 * label: 'Input button',
8511 * $( 'body' ).append( button.$element );
8513 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs
8516 * @extends OO.ui.InputWidget
8517 * @mixins OO.ui.mixin.ButtonElement
8518 * @mixins OO.ui.mixin.IconElement
8519 * @mixins OO.ui.mixin.IndicatorElement
8520 * @mixins OO.ui.mixin.LabelElement
8521 * @mixins OO.ui.mixin.TitledElement
8524 * @param {Object} [config] Configuration options
8525 * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'.
8526 * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default.
8527 * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators},
8528 * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only
8529 * be set to `true` when there’s need to support IE 6 in a form with multiple buttons.
8531 OO
.ui
.ButtonInputWidget
= function OoUiButtonInputWidget( config
) {
8532 // Configuration initialization
8533 config
= $.extend( { type
: 'button', useInputTag
: false }, config
);
8535 // See InputWidget#reusePreInfuseDOM about config.$input
8536 if ( config
.$input
) {
8537 config
.$input
.empty();
8540 // Properties (must be set before parent constructor, which calls #setValue)
8541 this.useInputTag
= config
.useInputTag
;
8543 // Parent constructor
8544 OO
.ui
.ButtonInputWidget
.parent
.call( this, config
);
8546 // Mixin constructors
8547 OO
.ui
.mixin
.ButtonElement
.call( this, $.extend( {}, config
, { $button
: this.$input
} ) );
8548 OO
.ui
.mixin
.IconElement
.call( this, config
);
8549 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
8550 OO
.ui
.mixin
.LabelElement
.call( this, config
);
8551 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$input
} ) );
8554 if ( !config
.useInputTag
) {
8555 this.$input
.append( this.$icon
, this.$label
, this.$indicator
);
8557 this.$element
.addClass( 'oo-ui-buttonInputWidget' );
8562 OO
.inheritClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.InputWidget
);
8563 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.ButtonElement
);
8564 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IconElement
);
8565 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
8566 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.LabelElement
);
8567 OO
.mixinClass( OO
.ui
.ButtonInputWidget
, OO
.ui
.mixin
.TitledElement
);
8569 /* Static Properties */
8575 OO
.ui
.ButtonInputWidget
.static.tagName
= 'span';
8583 OO
.ui
.ButtonInputWidget
.prototype.getInputElement = function ( config
) {
8585 type
= [ 'button', 'submit', 'reset' ].indexOf( config
.type
) !== -1 ? config
.type
: 'button';
8586 return $( '<' + ( config
.useInputTag
? 'input' : 'button' ) + ' type="' + type
+ '">' );
8592 * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag.
8594 * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or
8595 * text, or `null` for no label
8598 OO
.ui
.ButtonInputWidget
.prototype.setLabel = function ( label
) {
8599 if ( typeof label
=== 'function' ) {
8600 label
= OO
.ui
.resolveMsg( label
);
8603 if ( this.useInputTag
) {
8604 // Discard non-plaintext labels
8605 if ( typeof label
!== 'string' ) {
8609 this.$input
.val( label
);
8612 return OO
.ui
.mixin
.LabelElement
.prototype.setLabel
.call( this, label
);
8616 * Set the value of the input.
8618 * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as
8619 * they do not support {@link #value values}.
8621 * @param {string} value New value
8624 OO
.ui
.ButtonInputWidget
.prototype.setValue = function ( value
) {
8625 if ( !this.useInputTag
) {
8626 OO
.ui
.ButtonInputWidget
.parent
.prototype.setValue
.call( this, value
);
8634 OO
.ui
.ButtonInputWidget
.prototype.getInputId = function () {
8635 // Disable generating `<label>` elements for buttons. One would very rarely need additional label
8636 // for a button, and it's already a big clickable target, and it causes unexpected rendering.
8641 * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value.
8642 * Note that these {@link OO.ui.InputWidget input widgets} are best laid out
8643 * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline}
8644 * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1].
8646 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8649 * // An example of selected, unselected, and disabled checkbox inputs
8650 * var checkbox1=new OO.ui.CheckboxInputWidget( {
8654 * var checkbox2=new OO.ui.CheckboxInputWidget( {
8657 * var checkbox3=new OO.ui.CheckboxInputWidget( {
8661 * // Create a fieldset layout with fields for each checkbox.
8662 * var fieldset = new OO.ui.FieldsetLayout( {
8663 * label: 'Checkboxes'
8665 * fieldset.addItems( [
8666 * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ),
8667 * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ),
8668 * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ),
8670 * $( 'body' ).append( fieldset.$element );
8672 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8675 * @extends OO.ui.InputWidget
8678 * @param {Object} [config] Configuration options
8679 * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected.
8681 OO
.ui
.CheckboxInputWidget
= function OoUiCheckboxInputWidget( config
) {
8682 // Configuration initialization
8683 config
= config
|| {};
8685 // Parent constructor
8686 OO
.ui
.CheckboxInputWidget
.parent
.call( this, config
);
8690 .addClass( 'oo-ui-checkboxInputWidget' )
8691 // Required for pretty styling in WikimediaUI theme
8692 .append( $( '<span>' ) );
8693 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
8698 OO
.inheritClass( OO
.ui
.CheckboxInputWidget
, OO
.ui
.InputWidget
);
8700 /* Static Properties */
8706 OO
.ui
.CheckboxInputWidget
.static.tagName
= 'span';
8708 /* Static Methods */
8713 OO
.ui
.CheckboxInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
8714 var state
= OO
.ui
.CheckboxInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
8715 state
.checked
= config
.$input
.prop( 'checked' );
8725 OO
.ui
.CheckboxInputWidget
.prototype.getInputElement = function () {
8726 return $( '<input>' ).attr( 'type', 'checkbox' );
8732 OO
.ui
.CheckboxInputWidget
.prototype.onEdit = function () {
8734 if ( !this.isDisabled() ) {
8735 // Allow the stack to clear so the value will be updated
8736 setTimeout( function () {
8737 widget
.setSelected( widget
.$input
.prop( 'checked' ) );
8743 * Set selection state of this checkbox.
8745 * @param {boolean} state `true` for selected
8748 OO
.ui
.CheckboxInputWidget
.prototype.setSelected = function ( state
) {
8750 if ( this.selected
!== state
) {
8751 this.selected
= state
;
8752 this.$input
.prop( 'checked', this.selected
);
8753 this.emit( 'change', this.selected
);
8759 * Check if this checkbox is selected.
8761 * @return {boolean} Checkbox is selected
8763 OO
.ui
.CheckboxInputWidget
.prototype.isSelected = function () {
8764 // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify
8765 // it, and we won't know unless they're kind enough to trigger a 'change' event.
8766 var selected
= this.$input
.prop( 'checked' );
8767 if ( this.selected
!== selected
) {
8768 this.setSelected( selected
);
8770 return this.selected
;
8776 OO
.ui
.CheckboxInputWidget
.prototype.simulateLabelClick = function () {
8777 if ( !this.isDisabled() ) {
8778 this.$input
.click();
8786 OO
.ui
.CheckboxInputWidget
.prototype.restorePreInfuseState = function ( state
) {
8787 OO
.ui
.CheckboxInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
8788 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
8789 this.setSelected( state
.checked
);
8794 * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used
8795 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
8796 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
8797 * more information about input widgets.
8799 * A DropdownInputWidget always has a value (one of the options is always selected), unless there
8800 * are no options. If no `value` configuration option is provided, the first option is selected.
8801 * If you need a state representing no value (no option being selected), use a DropdownWidget.
8803 * This and OO.ui.RadioSelectInputWidget support the same configuration options.
8806 * // Example: A DropdownInputWidget with three options
8807 * var dropdownInput = new OO.ui.DropdownInputWidget( {
8809 * { data: 'a', label: 'First' },
8810 * { data: 'b', label: 'Second'},
8811 * { data: 'c', label: 'Third' }
8814 * $( 'body' ).append( dropdownInput.$element );
8816 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8819 * @extends OO.ui.InputWidget
8820 * @mixins OO.ui.mixin.TitledElement
8823 * @param {Object} [config] Configuration options
8824 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
8825 * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget}
8827 OO
.ui
.DropdownInputWidget
= function OoUiDropdownInputWidget( config
) {
8828 // Configuration initialization
8829 config
= config
|| {};
8831 // See InputWidget#reusePreInfuseDOM about config.$input
8832 if ( config
.$input
) {
8833 config
.$input
.addClass( 'oo-ui-element-hidden' );
8836 // Properties (must be done before parent constructor which calls #setDisabled)
8837 this.dropdownWidget
= new OO
.ui
.DropdownWidget( config
.dropdown
);
8839 // Parent constructor
8840 OO
.ui
.DropdownInputWidget
.parent
.call( this, config
);
8842 // Mixin constructors
8843 OO
.ui
.mixin
.TitledElement
.call( this, config
);
8846 this.dropdownWidget
.getMenu().connect( this, { select
: 'onMenuSelect' } );
8849 this.setOptions( config
.options
|| [] );
8851 .addClass( 'oo-ui-dropdownInputWidget' )
8852 .append( this.dropdownWidget
.$element
);
8853 this.setTabIndexedElement( null );
8858 OO
.inheritClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.InputWidget
);
8859 OO
.mixinClass( OO
.ui
.DropdownInputWidget
, OO
.ui
.mixin
.TitledElement
);
8867 OO
.ui
.DropdownInputWidget
.prototype.getInputElement = function () {
8868 return $( '<input>' ).attr( 'type', 'hidden' );
8872 * Handles menu select events.
8875 * @param {OO.ui.MenuOptionWidget} item Selected menu item
8877 OO
.ui
.DropdownInputWidget
.prototype.onMenuSelect = function ( item
) {
8878 this.setValue( item
.getData() );
8884 OO
.ui
.DropdownInputWidget
.prototype.setValue = function ( value
) {
8886 value
= this.cleanUpValue( value
);
8887 this.dropdownWidget
.getMenu().selectItemByData( value
);
8888 // Only allow setting values that are actually present in the dropdown
8889 selected
= this.dropdownWidget
.getMenu().getSelectedItem();
8890 value
= selected
? selected
.getData() : '';
8891 OO
.ui
.DropdownInputWidget
.parent
.prototype.setValue
.call( this, value
);
8898 OO
.ui
.DropdownInputWidget
.prototype.setDisabled = function ( state
) {
8899 this.dropdownWidget
.setDisabled( state
);
8900 OO
.ui
.DropdownInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
8905 * Set the options available for this input.
8907 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
8910 OO
.ui
.DropdownInputWidget
.prototype.setOptions = function ( options
) {
8912 value
= this.getValue(),
8915 // Rebuild the dropdown menu
8916 this.dropdownWidget
.getMenu()
8918 .addItems( options
.map( function ( opt
) {
8919 var optValue
= widget
.cleanUpValue( opt
.data
);
8921 if ( opt
.optgroup
=== undefined ) {
8922 return new OO
.ui
.MenuOptionWidget( {
8924 label
: opt
.label
!== undefined ? opt
.label
: optValue
8927 return new OO
.ui
.MenuSectionOptionWidget( {
8933 // Restore the previous value, or reset to something sensible
8934 if ( this.dropdownWidget
.getMenu().getItemFromData( value
) ) {
8935 // Previous value is still available, ensure consistency with the dropdown
8936 this.setValue( value
);
8938 // No longer valid, reset
8939 if ( options
.length
) {
8940 this.setValue( options
[ 0 ].data
);
8950 OO
.ui
.DropdownInputWidget
.prototype.focus = function () {
8951 this.dropdownWidget
.focus();
8958 OO
.ui
.DropdownInputWidget
.prototype.blur = function () {
8959 this.dropdownWidget
.blur();
8964 * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set,
8965 * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select}
8966 * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information,
8967 * please see the [OOjs UI documentation on MediaWiki][1].
8969 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
8972 * // An example of selected, unselected, and disabled radio inputs
8973 * var radio1 = new OO.ui.RadioInputWidget( {
8977 * var radio2 = new OO.ui.RadioInputWidget( {
8980 * var radio3 = new OO.ui.RadioInputWidget( {
8984 * // Create a fieldset layout with fields for each radio button.
8985 * var fieldset = new OO.ui.FieldsetLayout( {
8986 * label: 'Radio inputs'
8988 * fieldset.addItems( [
8989 * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ),
8990 * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ),
8991 * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ),
8993 * $( 'body' ).append( fieldset.$element );
8995 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
8998 * @extends OO.ui.InputWidget
9001 * @param {Object} [config] Configuration options
9002 * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected.
9004 OO
.ui
.RadioInputWidget
= function OoUiRadioInputWidget( config
) {
9005 // Configuration initialization
9006 config
= config
|| {};
9008 // Parent constructor
9009 OO
.ui
.RadioInputWidget
.parent
.call( this, config
);
9013 .addClass( 'oo-ui-radioInputWidget' )
9014 // Required for pretty styling in WikimediaUI theme
9015 .append( $( '<span>' ) );
9016 this.setSelected( config
.selected
!== undefined ? config
.selected
: false );
9021 OO
.inheritClass( OO
.ui
.RadioInputWidget
, OO
.ui
.InputWidget
);
9023 /* Static Properties */
9029 OO
.ui
.RadioInputWidget
.static.tagName
= 'span';
9031 /* Static Methods */
9036 OO
.ui
.RadioInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9037 var state
= OO
.ui
.RadioInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9038 state
.checked
= config
.$input
.prop( 'checked' );
9048 OO
.ui
.RadioInputWidget
.prototype.getInputElement = function () {
9049 return $( '<input>' ).attr( 'type', 'radio' );
9055 OO
.ui
.RadioInputWidget
.prototype.onEdit = function () {
9056 // RadioInputWidget doesn't track its state.
9060 * Set selection state of this radio button.
9062 * @param {boolean} state `true` for selected
9065 OO
.ui
.RadioInputWidget
.prototype.setSelected = function ( state
) {
9066 // RadioInputWidget doesn't track its state.
9067 this.$input
.prop( 'checked', state
);
9072 * Check if this radio button is selected.
9074 * @return {boolean} Radio is selected
9076 OO
.ui
.RadioInputWidget
.prototype.isSelected = function () {
9077 return this.$input
.prop( 'checked' );
9083 OO
.ui
.RadioInputWidget
.prototype.simulateLabelClick = function () {
9084 if ( !this.isDisabled() ) {
9085 this.$input
.click();
9093 OO
.ui
.RadioInputWidget
.prototype.restorePreInfuseState = function ( state
) {
9094 OO
.ui
.RadioInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
9095 if ( state
.checked
!== undefined && state
.checked
!== this.isSelected() ) {
9096 this.setSelected( state
.checked
);
9101 * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used
9102 * within an HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value
9103 * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for
9104 * more information about input widgets.
9106 * This and OO.ui.DropdownInputWidget support the same configuration options.
9109 * // Example: A RadioSelectInputWidget with three options
9110 * var radioSelectInput = new OO.ui.RadioSelectInputWidget( {
9112 * { data: 'a', label: 'First' },
9113 * { data: 'b', label: 'Second'},
9114 * { data: 'c', label: 'Third' }
9117 * $( 'body' ).append( radioSelectInput.$element );
9119 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9122 * @extends OO.ui.InputWidget
9125 * @param {Object} [config] Configuration options
9126 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
9128 OO
.ui
.RadioSelectInputWidget
= function OoUiRadioSelectInputWidget( config
) {
9129 // Configuration initialization
9130 config
= config
|| {};
9132 // Properties (must be done before parent constructor which calls #setDisabled)
9133 this.radioSelectWidget
= new OO
.ui
.RadioSelectWidget();
9135 // Parent constructor
9136 OO
.ui
.RadioSelectInputWidget
.parent
.call( this, config
);
9139 this.radioSelectWidget
.connect( this, { select
: 'onMenuSelect' } );
9142 this.setOptions( config
.options
|| [] );
9144 .addClass( 'oo-ui-radioSelectInputWidget' )
9145 .append( this.radioSelectWidget
.$element
);
9146 this.setTabIndexedElement( null );
9151 OO
.inheritClass( OO
.ui
.RadioSelectInputWidget
, OO
.ui
.InputWidget
);
9153 /* Static Methods */
9158 OO
.ui
.RadioSelectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9159 var state
= OO
.ui
.RadioSelectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9160 state
.value
= $( node
).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val();
9167 OO
.ui
.RadioSelectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9168 config
= OO
.ui
.RadioSelectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9169 // Cannot reuse the `<input type=radio>` set
9170 delete config
.$input
;
9180 OO
.ui
.RadioSelectInputWidget
.prototype.getInputElement = function () {
9181 return $( '<input>' ).attr( 'type', 'hidden' );
9185 * Handles menu select events.
9188 * @param {OO.ui.RadioOptionWidget} item Selected menu item
9190 OO
.ui
.RadioSelectInputWidget
.prototype.onMenuSelect = function ( item
) {
9191 this.setValue( item
.getData() );
9197 OO
.ui
.RadioSelectInputWidget
.prototype.setValue = function ( value
) {
9198 value
= this.cleanUpValue( value
);
9199 this.radioSelectWidget
.selectItemByData( value
);
9200 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9207 OO
.ui
.RadioSelectInputWidget
.prototype.setDisabled = function ( state
) {
9208 this.radioSelectWidget
.setDisabled( state
);
9209 OO
.ui
.RadioSelectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9214 * Set the options available for this input.
9216 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
9219 OO
.ui
.RadioSelectInputWidget
.prototype.setOptions = function ( options
) {
9221 value
= this.getValue(),
9224 // Rebuild the radioSelect menu
9225 this.radioSelectWidget
9227 .addItems( options
.map( function ( opt
) {
9228 var optValue
= widget
.cleanUpValue( opt
.data
);
9229 return new OO
.ui
.RadioOptionWidget( {
9231 label
: opt
.label
!== undefined ? opt
.label
: optValue
9235 // Restore the previous value, or reset to something sensible
9236 if ( this.radioSelectWidget
.getItemFromData( value
) ) {
9237 // Previous value is still available, ensure consistency with the radioSelect
9238 this.setValue( value
);
9240 // No longer valid, reset
9241 if ( options
.length
) {
9242 this.setValue( options
[ 0 ].data
);
9252 OO
.ui
.RadioSelectInputWidget
.prototype.focus = function () {
9253 this.radioSelectWidget
.focus();
9260 OO
.ui
.RadioSelectInputWidget
.prototype.blur = function () {
9261 this.radioSelectWidget
.blur();
9266 * CheckboxMultiselectInputWidget is a
9267 * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a
9268 * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of
9269 * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for
9270 * more information about input widgets.
9273 * // Example: A CheckboxMultiselectInputWidget with three options
9274 * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( {
9276 * { data: 'a', label: 'First' },
9277 * { data: 'b', label: 'Second'},
9278 * { data: 'c', label: 'Third' }
9281 * $( 'body' ).append( multiselectInput.$element );
9283 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9286 * @extends OO.ui.InputWidget
9289 * @param {Object} [config] Configuration options
9290 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: …, disabled: … }`
9292 OO
.ui
.CheckboxMultiselectInputWidget
= function OoUiCheckboxMultiselectInputWidget( config
) {
9293 // Configuration initialization
9294 config
= config
|| {};
9296 // Properties (must be done before parent constructor which calls #setDisabled)
9297 this.checkboxMultiselectWidget
= new OO
.ui
.CheckboxMultiselectWidget();
9299 // Parent constructor
9300 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.call( this, config
);
9303 this.inputName
= config
.name
;
9307 .addClass( 'oo-ui-checkboxMultiselectInputWidget' )
9308 .append( this.checkboxMultiselectWidget
.$element
);
9309 // We don't use this.$input, but rather the CheckboxInputWidgets inside each option
9310 this.$input
.detach();
9311 this.setOptions( config
.options
|| [] );
9312 // Have to repeat this from parent, as we need options to be set up for this to make sense
9313 this.setValue( config
.value
);
9318 OO
.inheritClass( OO
.ui
.CheckboxMultiselectInputWidget
, OO
.ui
.InputWidget
);
9320 /* Static Methods */
9325 OO
.ui
.CheckboxMultiselectInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9326 var state
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9327 state
.value
= $( node
).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9328 .toArray().map( function ( el
) { return el
.value
; } );
9335 OO
.ui
.CheckboxMultiselectInputWidget
.static.reusePreInfuseDOM = function ( node
, config
) {
9336 config
= OO
.ui
.CheckboxMultiselectInputWidget
.parent
.static.reusePreInfuseDOM( node
, config
);
9337 // Cannot reuse the `<input type=checkbox>` set
9338 delete config
.$input
;
9348 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getInputElement = function () {
9350 return $( '<unused>' );
9356 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.getValue = function () {
9357 var value
= this.$element
.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' )
9358 .toArray().map( function ( el
) { return el
.value
; } );
9359 if ( this.value
!== value
) {
9360 this.setValue( value
);
9368 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setValue = function ( value
) {
9369 value
= this.cleanUpValue( value
);
9370 this.checkboxMultiselectWidget
.selectItemsByData( value
);
9371 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setValue
.call( this, value
);
9376 * Clean up incoming value.
9378 * @param {string[]} value Original value
9379 * @return {string[]} Cleaned up value
9381 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.cleanUpValue = function ( value
) {
9384 if ( !Array
.isArray( value
) ) {
9387 for ( i
= 0; i
< value
.length
; i
++ ) {
9389 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( this, value
[ i
] );
9390 // Remove options that we don't have here
9391 if ( !this.checkboxMultiselectWidget
.getItemFromData( singleValue
) ) {
9394 cleanValue
.push( singleValue
);
9402 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setDisabled = function ( state
) {
9403 this.checkboxMultiselectWidget
.setDisabled( state
);
9404 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.setDisabled
.call( this, state
);
9409 * Set the options available for this input.
9411 * @param {Object[]} options Array of menu options in the format `{ data: …, label: …, disabled: … }`
9414 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.setOptions = function ( options
) {
9417 // Rebuild the checkboxMultiselectWidget menu
9418 this.checkboxMultiselectWidget
9420 .addItems( options
.map( function ( opt
) {
9421 var optValue
, item
, optDisabled
;
9423 OO
.ui
.CheckboxMultiselectInputWidget
.parent
.prototype.cleanUpValue
.call( widget
, opt
.data
);
9424 optDisabled
= opt
.disabled
!== undefined ? opt
.disabled
: false;
9425 item
= new OO
.ui
.CheckboxMultioptionWidget( {
9427 label
: opt
.label
!== undefined ? opt
.label
: optValue
,
9428 disabled
: optDisabled
9430 // Set the 'name' and 'value' for form submission
9431 item
.checkbox
.$input
.attr( 'name', widget
.inputName
);
9432 item
.checkbox
.setValue( optValue
);
9436 // Re-set the value, checking the checkboxes as needed.
9437 // This will also get rid of any stale options that we just removed.
9438 this.setValue( this.getValue() );
9446 OO
.ui
.CheckboxMultiselectInputWidget
.prototype.focus = function () {
9447 this.checkboxMultiselectWidget
.focus();
9452 * TextInputWidgets, like HTML text inputs, can be configured with options that customize the
9453 * size of the field as well as its presentation. In addition, these widgets can be configured
9454 * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional
9455 * validation-pattern (used to determine if an input value is valid or not) and an input filter,
9456 * which modifies incoming values rather than validating them.
9457 * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
9459 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
9462 * // Example of a text input widget
9463 * var textInput = new OO.ui.TextInputWidget( {
9464 * value: 'Text input'
9466 * $( 'body' ).append( textInput.$element );
9468 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
9471 * @extends OO.ui.InputWidget
9472 * @mixins OO.ui.mixin.IconElement
9473 * @mixins OO.ui.mixin.IndicatorElement
9474 * @mixins OO.ui.mixin.PendingElement
9475 * @mixins OO.ui.mixin.LabelElement
9478 * @param {Object} [config] Configuration options
9479 * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password'
9480 * 'email', 'url' or 'number'. Ignored if `multiline` is true.
9481 * @cfg {string} [placeholder] Placeholder text
9482 * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to
9483 * instruct the browser to focus this widget.
9484 * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input.
9485 * @cfg {number} [maxLength] Maximum number of characters allowed in the input.
9486 * @cfg {boolean} [multiline=false] Allow multiple lines of text
9487 * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`,
9488 * specifies minimum number of rows to display.
9489 * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content.
9490 * Use the #maxRows config to specify a maximum number of displayed rows.
9491 * @cfg {number} [maxRows] Maximum number of rows to display when #autosize is set to true.
9492 * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided.
9493 * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of
9494 * the value or placeholder text: `'before'` or `'after'`
9495 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
9496 * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field
9497 * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a
9498 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer'
9499 * (the value must contain only numbers); when RegExp, a regular expression that must match the
9500 * value for it to be considered valid; when Function, a function receiving the value as parameter
9501 * that must return true, or promise resolving to true, for it to be considered valid.
9503 OO
.ui
.TextInputWidget
= function OoUiTextInputWidget( config
) {
9504 // Configuration initialization
9505 config
= $.extend( {
9507 labelPosition
: 'after'
9510 // Parent constructor
9511 OO
.ui
.TextInputWidget
.parent
.call( this, config
);
9513 // Mixin constructors
9514 OO
.ui
.mixin
.IconElement
.call( this, config
);
9515 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
9516 OO
.ui
.mixin
.PendingElement
.call( this, $.extend( {}, config
, { $pending
: this.$input
} ) );
9517 OO
.ui
.mixin
.LabelElement
.call( this, config
);
9520 this.type
= this.getSaneType( config
);
9521 this.readOnly
= false;
9522 this.required
= false;
9523 this.multiline
= !!config
.multiline
;
9524 this.autosize
= !!config
.autosize
;
9525 this.minRows
= config
.rows
!== undefined ? config
.rows
: '';
9526 this.maxRows
= config
.maxRows
|| Math
.max( 2 * ( this.minRows
|| 0 ), 10 );
9527 this.validate
= null;
9528 this.styleHeight
= null;
9529 this.scrollWidth
= null;
9531 // Clone for resizing
9532 if ( this.autosize
) {
9533 this.$clone
= this.$input
9535 .insertAfter( this.$input
)
9536 .attr( 'aria-hidden', 'true' )
9537 .addClass( 'oo-ui-element-hidden' );
9540 this.setValidation( config
.validate
);
9541 this.setLabelPosition( config
.labelPosition
);
9545 keypress
: this.onKeyPress
.bind( this ),
9546 blur
: this.onBlur
.bind( this ),
9547 focus
: this.onFocus
.bind( this )
9549 this.$icon
.on( 'mousedown', this.onIconMouseDown
.bind( this ) );
9550 this.$indicator
.on( 'mousedown', this.onIndicatorMouseDown
.bind( this ) );
9551 this.on( 'labelChange', this.updatePosition
.bind( this ) );
9552 this.connect( this, {
9555 this.on( 'change', OO
.ui
.debounce( this.onDebouncedChange
.bind( this ), 250 ) );
9559 .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type
)
9560 .append( this.$icon
, this.$indicator
);
9561 this.setReadOnly( !!config
.readOnly
);
9562 this.setRequired( !!config
.required
);
9563 if ( config
.placeholder
!== undefined ) {
9564 this.$input
.attr( 'placeholder', config
.placeholder
);
9566 if ( config
.maxLength
!== undefined ) {
9567 this.$input
.attr( 'maxlength', config
.maxLength
);
9569 if ( config
.autofocus
) {
9570 this.$input
.attr( 'autofocus', 'autofocus' );
9572 if ( config
.autocomplete
=== false ) {
9573 this.$input
.attr( 'autocomplete', 'off' );
9574 // Turning off autocompletion also disables "form caching" when the user navigates to a
9575 // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI.
9577 beforeunload: function () {
9578 this.$input
.removeAttr( 'autocomplete' );
9580 pageshow: function () {
9581 // Browsers don't seem to actually fire this event on "Back", they instead just reload the
9582 // whole page... it shouldn't hurt, though.
9583 this.$input
.attr( 'autocomplete', 'off' );
9587 if ( this.multiline
&& config
.rows
) {
9588 this.$input
.attr( 'rows', config
.rows
);
9590 if ( this.label
|| config
.autosize
) {
9591 this.isWaitingToBeAttached
= true;
9592 this.installParentChangeDetector();
9598 OO
.inheritClass( OO
.ui
.TextInputWidget
, OO
.ui
.InputWidget
);
9599 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IconElement
);
9600 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
9601 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.PendingElement
);
9602 OO
.mixinClass( OO
.ui
.TextInputWidget
, OO
.ui
.mixin
.LabelElement
);
9604 /* Static Properties */
9606 OO
.ui
.TextInputWidget
.static.validationPatterns
= {
9611 /* Static Methods */
9616 OO
.ui
.TextInputWidget
.static.gatherPreInfuseState = function ( node
, config
) {
9617 var state
= OO
.ui
.TextInputWidget
.parent
.static.gatherPreInfuseState( node
, config
);
9618 if ( config
.multiline
) {
9619 state
.scrollTop
= config
.$input
.scrollTop();
9627 * An `enter` event is emitted when the user presses 'enter' inside the text box.
9629 * Not emitted if the input is multiline.
9635 * A `resize` event is emitted when autosize is set and the widget resizes
9643 * Handle icon mouse down events.
9646 * @param {jQuery.Event} e Mouse down event
9648 OO
.ui
.TextInputWidget
.prototype.onIconMouseDown = function ( e
) {
9649 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9656 * Handle indicator mouse down events.
9659 * @param {jQuery.Event} e Mouse down event
9661 OO
.ui
.TextInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
9662 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
9669 * Handle key press events.
9672 * @param {jQuery.Event} e Key press event
9673 * @fires enter If enter key is pressed and input is not multiline
9675 OO
.ui
.TextInputWidget
.prototype.onKeyPress = function ( e
) {
9676 if ( e
.which
=== OO
.ui
.Keys
.ENTER
&& !this.multiline
) {
9677 this.emit( 'enter', e
);
9682 * Handle blur events.
9685 * @param {jQuery.Event} e Blur event
9687 OO
.ui
.TextInputWidget
.prototype.onBlur = function () {
9688 this.setValidityFlag();
9692 * Handle focus events.
9695 * @param {jQuery.Event} e Focus event
9697 OO
.ui
.TextInputWidget
.prototype.onFocus = function () {
9698 if ( this.isWaitingToBeAttached
) {
9699 // If we've received focus, then we must be attached to the document, and if
9700 // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now.
9701 this.onElementAttach();
9703 this.setValidityFlag( true );
9707 * Handle element attach events.
9710 * @param {jQuery.Event} e Element attach event
9712 OO
.ui
.TextInputWidget
.prototype.onElementAttach = function () {
9713 this.isWaitingToBeAttached
= false;
9714 // Any previously calculated size is now probably invalid if we reattached elsewhere
9715 this.valCache
= null;
9717 this.positionLabel();
9721 * Handle change events.
9723 * @param {string} value
9726 OO
.ui
.TextInputWidget
.prototype.onChange = function () {
9731 * Handle debounced change events.
9733 * @param {string} value
9736 OO
.ui
.TextInputWidget
.prototype.onDebouncedChange = function () {
9737 this.setValidityFlag();
9741 * Check if the input is {@link #readOnly read-only}.
9745 OO
.ui
.TextInputWidget
.prototype.isReadOnly = function () {
9746 return this.readOnly
;
9750 * Set the {@link #readOnly read-only} state of the input.
9752 * @param {boolean} state Make input read-only
9755 OO
.ui
.TextInputWidget
.prototype.setReadOnly = function ( state
) {
9756 this.readOnly
= !!state
;
9757 this.$input
.prop( 'readOnly', this.readOnly
);
9762 * Check if the input is {@link #required required}.
9766 OO
.ui
.TextInputWidget
.prototype.isRequired = function () {
9767 return this.required
;
9771 * Set the {@link #required required} state of the input.
9773 * @param {boolean} state Make input required
9776 OO
.ui
.TextInputWidget
.prototype.setRequired = function ( state
) {
9777 this.required
= !!state
;
9778 if ( this.required
) {
9780 .prop( 'required', true )
9781 .attr( 'aria-required', 'true' );
9782 if ( this.getIndicator() === null ) {
9783 this.setIndicator( 'required' );
9787 .prop( 'required', false )
9788 .removeAttr( 'aria-required' );
9789 if ( this.getIndicator() === 'required' ) {
9790 this.setIndicator( null );
9797 * Support function for making #onElementAttach work across browsers.
9799 * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument
9800 * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback.
9802 * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the
9803 * first time that the element gets attached to the documented.
9805 OO
.ui
.TextInputWidget
.prototype.installParentChangeDetector = function () {
9806 var mutationObserver
, onRemove
, topmostNode
, fakeParentNode
,
9807 MutationObserver
= window
.MutationObserver
|| window
.WebKitMutationObserver
|| window
.MozMutationObserver
,
9810 if ( MutationObserver
) {
9811 // The new way. If only it wasn't so ugly.
9813 if ( this.isElementAttached() ) {
9814 // Widget is attached already, do nothing. This breaks the functionality of this function when
9815 // the widget is detached and reattached. Alas, doing this correctly with MutationObserver
9816 // would require observation of the whole document, which would hurt performance of other,
9817 // more important code.
9821 // Find topmost node in the tree
9822 topmostNode
= this.$element
[ 0 ];
9823 while ( topmostNode
.parentNode
) {
9824 topmostNode
= topmostNode
.parentNode
;
9827 // We have no way to detect the $element being attached somewhere without observing the entire
9828 // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the
9829 // parent node of $element, and instead detect when $element is removed from it (and thus
9830 // probably attached somewhere else). If there is no parent, we create a "fake" one. If it
9831 // doesn't get attached, we end up back here and create the parent.
9833 mutationObserver
= new MutationObserver( function ( mutations
) {
9834 var i
, j
, removedNodes
;
9835 for ( i
= 0; i
< mutations
.length
; i
++ ) {
9836 removedNodes
= mutations
[ i
].removedNodes
;
9837 for ( j
= 0; j
< removedNodes
.length
; j
++ ) {
9838 if ( removedNodes
[ j
] === topmostNode
) {
9839 setTimeout( onRemove
, 0 );
9846 onRemove = function () {
9847 // If the node was attached somewhere else, report it
9848 if ( widget
.isElementAttached() ) {
9849 widget
.onElementAttach();
9851 mutationObserver
.disconnect();
9852 widget
.installParentChangeDetector();
9855 // Create a fake parent and observe it
9856 fakeParentNode
= $( '<div>' ).append( topmostNode
)[ 0 ];
9857 mutationObserver
.observe( fakeParentNode
, { childList
: true } );
9859 // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for
9860 // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated.
9861 this.$element
.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach
.bind( this ) );
9866 * Automatically adjust the size of the text input.
9868 * This only affects #multiline inputs that are {@link #autosize autosized}.
9873 OO
.ui
.TextInputWidget
.prototype.adjustSize = function () {
9874 var scrollHeight
, innerHeight
, outerHeight
, maxInnerHeight
, measurementError
,
9875 idealHeight
, newHeight
, scrollWidth
, property
;
9877 if ( this.isWaitingToBeAttached
) {
9878 // #onElementAttach will be called soon, which calls this method
9882 if ( this.multiline
&& this.$input
.val() !== this.valCache
) {
9883 if ( this.autosize
) {
9885 .val( this.$input
.val() )
9886 .attr( 'rows', this.minRows
)
9887 // Set inline height property to 0 to measure scroll height
9888 .css( 'height', 0 );
9890 this.$clone
.removeClass( 'oo-ui-element-hidden' );
9892 this.valCache
= this.$input
.val();
9894 scrollHeight
= this.$clone
[ 0 ].scrollHeight
;
9896 // Remove inline height property to measure natural heights
9897 this.$clone
.css( 'height', '' );
9898 innerHeight
= this.$clone
.innerHeight();
9899 outerHeight
= this.$clone
.outerHeight();
9901 // Measure max rows height
9903 .attr( 'rows', this.maxRows
)
9904 .css( 'height', 'auto' )
9906 maxInnerHeight
= this.$clone
.innerHeight();
9908 // Difference between reported innerHeight and scrollHeight with no scrollbars present.
9909 // This is sometimes non-zero on Blink-based browsers, depending on zoom level.
9910 measurementError
= maxInnerHeight
- this.$clone
[ 0 ].scrollHeight
;
9911 idealHeight
= Math
.min( maxInnerHeight
, scrollHeight
+ measurementError
);
9913 this.$clone
.addClass( 'oo-ui-element-hidden' );
9915 // Only apply inline height when expansion beyond natural height is needed
9916 // Use the difference between the inner and outer height as a buffer
9917 newHeight
= idealHeight
> innerHeight
? idealHeight
+ ( outerHeight
- innerHeight
) : '';
9918 if ( newHeight
!== this.styleHeight
) {
9919 this.$input
.css( 'height', newHeight
);
9920 this.styleHeight
= newHeight
;
9921 this.emit( 'resize' );
9924 scrollWidth
= this.$input
[ 0 ].offsetWidth
- this.$input
[ 0 ].clientWidth
;
9925 if ( scrollWidth
!== this.scrollWidth
) {
9926 property
= this.$element
.css( 'direction' ) === 'rtl' ? 'left' : 'right';
9928 this.$label
.css( { right
: '', left
: '' } );
9929 this.$indicator
.css( { right
: '', left
: '' } );
9931 if ( scrollWidth
) {
9932 this.$indicator
.css( property
, scrollWidth
);
9933 if ( this.labelPosition
=== 'after' ) {
9934 this.$label
.css( property
, scrollWidth
);
9938 this.scrollWidth
= scrollWidth
;
9939 this.positionLabel();
9949 OO
.ui
.TextInputWidget
.prototype.getInputElement = function ( config
) {
9950 if ( config
.multiline
) {
9951 return $( '<textarea>' );
9952 } else if ( this.getSaneType( config
) === 'number' ) {
9953 return $( '<input>' )
9954 .attr( 'step', 'any' )
9955 .attr( 'type', 'number' );
9957 return $( '<input>' ).attr( 'type', this.getSaneType( config
) );
9962 * Get sanitized value for 'type' for given config.
9964 * @param {Object} config Configuration options
9965 * @return {string|null}
9968 OO
.ui
.TextInputWidget
.prototype.getSaneType = function ( config
) {
9969 var allowedTypes
= [
9976 return allowedTypes
.indexOf( config
.type
) !== -1 ? config
.type
: 'text';
9980 * Check if the input supports multiple lines.
9984 OO
.ui
.TextInputWidget
.prototype.isMultiline = function () {
9985 return !!this.multiline
;
9989 * Check if the input automatically adjusts its size.
9993 OO
.ui
.TextInputWidget
.prototype.isAutosizing = function () {
9994 return !!this.autosize
;
9998 * Focus the input and select a specified range within the text.
10000 * @param {number} from Select from offset
10001 * @param {number} [to] Select to offset, defaults to from
10004 OO
.ui
.TextInputWidget
.prototype.selectRange = function ( from, to
) {
10005 var isBackwards
, start
, end
,
10006 input
= this.$input
[ 0 ];
10010 isBackwards
= to
< from;
10011 start
= isBackwards
? to
: from;
10012 end
= isBackwards
? from : to
;
10017 input
.setSelectionRange( start
, end
, isBackwards
? 'backward' : 'forward' );
10019 // IE throws an exception if you call setSelectionRange on a unattached DOM node.
10020 // Rather than expensively check if the input is attached every time, just check
10021 // if it was the cause of an error being thrown. If not, rethrow the error.
10022 if ( this.getElementDocument().body
.contains( input
) ) {
10030 * Get an object describing the current selection range in a directional manner
10032 * @return {Object} Object containing 'from' and 'to' offsets
10034 OO
.ui
.TextInputWidget
.prototype.getRange = function () {
10035 var input
= this.$input
[ 0 ],
10036 start
= input
.selectionStart
,
10037 end
= input
.selectionEnd
,
10038 isBackwards
= input
.selectionDirection
=== 'backward';
10041 from: isBackwards
? end
: start
,
10042 to
: isBackwards
? start
: end
10047 * Get the length of the text input value.
10049 * This could differ from the length of #getValue if the
10050 * value gets filtered
10052 * @return {number} Input length
10054 OO
.ui
.TextInputWidget
.prototype.getInputLength = function () {
10055 return this.$input
[ 0 ].value
.length
;
10059 * Focus the input and select the entire text.
10063 OO
.ui
.TextInputWidget
.prototype.select = function () {
10064 return this.selectRange( 0, this.getInputLength() );
10068 * Focus the input and move the cursor to the start.
10072 OO
.ui
.TextInputWidget
.prototype.moveCursorToStart = function () {
10073 return this.selectRange( 0 );
10077 * Focus the input and move the cursor to the end.
10081 OO
.ui
.TextInputWidget
.prototype.moveCursorToEnd = function () {
10082 return this.selectRange( this.getInputLength() );
10086 * Insert new content into the input.
10088 * @param {string} content Content to be inserted
10091 OO
.ui
.TextInputWidget
.prototype.insertContent = function ( content
) {
10093 range
= this.getRange(),
10094 value
= this.getValue();
10096 start
= Math
.min( range
.from, range
.to
);
10097 end
= Math
.max( range
.from, range
.to
);
10099 this.setValue( value
.slice( 0, start
) + content
+ value
.slice( end
) );
10100 this.selectRange( start
+ content
.length
);
10105 * Insert new content either side of a selection.
10107 * @param {string} pre Content to be inserted before the selection
10108 * @param {string} post Content to be inserted after the selection
10111 OO
.ui
.TextInputWidget
.prototype.encapsulateContent = function ( pre
, post
) {
10113 range
= this.getRange(),
10114 offset
= pre
.length
;
10116 start
= Math
.min( range
.from, range
.to
);
10117 end
= Math
.max( range
.from, range
.to
);
10119 this.selectRange( start
).insertContent( pre
);
10120 this.selectRange( offset
+ end
).insertContent( post
);
10122 this.selectRange( offset
+ start
, offset
+ end
);
10127 * Set the validation pattern.
10129 * The validation pattern is either a regular expression, a function, or the symbolic name of a
10130 * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the
10131 * value must contain only numbers).
10133 * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name
10134 * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class.
10136 OO
.ui
.TextInputWidget
.prototype.setValidation = function ( validate
) {
10137 if ( validate
instanceof RegExp
|| validate
instanceof Function
) {
10138 this.validate
= validate
;
10140 this.validate
= this.constructor.static.validationPatterns
[ validate
] || /.*/;
10145 * Sets the 'invalid' flag appropriately.
10147 * @param {boolean} [isValid] Optionally override validation result
10149 OO
.ui
.TextInputWidget
.prototype.setValidityFlag = function ( isValid
) {
10151 setFlag = function ( valid
) {
10153 widget
.$input
.attr( 'aria-invalid', 'true' );
10155 widget
.$input
.removeAttr( 'aria-invalid' );
10157 widget
.setFlags( { invalid
: !valid
} );
10160 if ( isValid
!== undefined ) {
10161 setFlag( isValid
);
10163 this.getValidity().then( function () {
10172 * Get the validity of current value.
10174 * This method returns a promise that resolves if the value is valid and rejects if
10175 * it isn't. Uses the {@link #validate validation pattern} to check for validity.
10177 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
10179 OO
.ui
.TextInputWidget
.prototype.getValidity = function () {
10182 function rejectOrResolve( valid
) {
10184 return $.Deferred().resolve().promise();
10186 return $.Deferred().reject().promise();
10190 // Check browser validity and reject if it is invalid
10192 this.$input
[ 0 ].checkValidity
!== undefined &&
10193 this.$input
[ 0 ].checkValidity() === false
10195 return rejectOrResolve( false );
10198 // Run our checks if the browser thinks the field is valid
10199 if ( this.validate
instanceof Function
) {
10200 result
= this.validate( this.getValue() );
10201 if ( result
&& $.isFunction( result
.promise
) ) {
10202 return result
.promise().then( function ( valid
) {
10203 return rejectOrResolve( valid
);
10206 return rejectOrResolve( result
);
10209 return rejectOrResolve( this.getValue().match( this.validate
) );
10214 * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`.
10216 * @param {string} labelPosition Label position, 'before' or 'after'
10219 OO
.ui
.TextInputWidget
.prototype.setLabelPosition = function ( labelPosition
) {
10220 this.labelPosition
= labelPosition
;
10221 if ( this.label
) {
10222 // If there is no label and we only change the position, #updatePosition is a no-op,
10223 // but it takes really a lot of work to do nothing.
10224 this.updatePosition();
10230 * Update the position of the inline label.
10232 * This method is called by #setLabelPosition, and can also be called on its own if
10233 * something causes the label to be mispositioned.
10237 OO
.ui
.TextInputWidget
.prototype.updatePosition = function () {
10238 var after
= this.labelPosition
=== 'after';
10241 .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label
&& after
)
10242 .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label
&& !after
);
10244 this.valCache
= null;
10245 this.scrollWidth
= null;
10247 this.positionLabel();
10253 * Position the label by setting the correct padding on the input.
10258 OO
.ui
.TextInputWidget
.prototype.positionLabel = function () {
10259 var after
, rtl
, property
;
10261 if ( this.isWaitingToBeAttached
) {
10262 // #onElementAttach will be called soon, which calls this method
10266 // Clear old values
10268 // Clear old values if present
10270 'padding-right': '',
10274 if ( this.label
) {
10275 this.$element
.append( this.$label
);
10277 this.$label
.detach();
10281 after
= this.labelPosition
=== 'after';
10282 rtl
= this.$element
.css( 'direction' ) === 'rtl';
10283 property
= after
=== rtl
? 'padding-left' : 'padding-right';
10285 this.$input
.css( property
, this.$label
.outerWidth( true ) + ( after
? this.scrollWidth
: 0 ) );
10293 OO
.ui
.TextInputWidget
.prototype.restorePreInfuseState = function ( state
) {
10294 OO
.ui
.TextInputWidget
.parent
.prototype.restorePreInfuseState
.call( this, state
);
10295 if ( state
.scrollTop
!== undefined ) {
10296 this.$input
.scrollTop( state
.scrollTop
);
10302 * @extends OO.ui.TextInputWidget
10305 * @param {Object} [config] Configuration options
10307 OO
.ui
.SearchInputWidget
= function OoUiSearchInputWidget( config
) {
10308 config
= $.extend( {
10312 // Set type to text so that TextInputWidget doesn't
10313 // get stuck in an infinite loop.
10314 config
.type
= 'text';
10316 // Parent constructor
10317 OO
.ui
.SearchInputWidget
.parent
.call( this, config
);
10320 this.$element
.addClass( 'oo-ui-textInputWidget-type-search' );
10321 this.updateSearchIndicator();
10322 this.connect( this, {
10323 disable
: 'onDisable'
10329 OO
.inheritClass( OO
.ui
.SearchInputWidget
, OO
.ui
.TextInputWidget
);
10337 OO
.ui
.SearchInputWidget
.prototype.getInputElement = function () {
10338 return $( '<input>' ).attr( 'type', 'search' );
10344 OO
.ui
.SearchInputWidget
.prototype.onIndicatorMouseDown = function ( e
) {
10345 if ( e
.which
=== OO
.ui
.MouseButtons
.LEFT
) {
10346 // Clear the text field
10347 this.setValue( '' );
10354 * Update the 'clear' indicator displayed on type: 'search' text
10355 * fields, hiding it when the field is already empty or when it's not
10358 OO
.ui
.SearchInputWidget
.prototype.updateSearchIndicator = function () {
10359 if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) {
10360 this.setIndicator( null );
10362 this.setIndicator( 'clear' );
10369 OO
.ui
.SearchInputWidget
.prototype.onChange = function () {
10370 OO
.ui
.SearchInputWidget
.parent
.prototype.onChange
.call( this );
10371 this.updateSearchIndicator();
10375 * Handle disable events.
10377 * @param {boolean} disabled Element is disabled
10380 OO
.ui
.SearchInputWidget
.prototype.onDisable = function () {
10381 this.updateSearchIndicator();
10387 OO
.ui
.SearchInputWidget
.prototype.setReadOnly = function ( state
) {
10388 OO
.ui
.SearchInputWidget
.parent
.prototype.setReadOnly
.call( this, state
);
10389 this.updateSearchIndicator();
10394 * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value
10395 * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which
10396 * a value can be chosen instead). Users can choose options from the combo box in one of two ways:
10398 * - by typing a value in the text input field. If the value exactly matches the value of a menu
10399 * option, that option will appear to be selected.
10400 * - by choosing a value from the menu. The value of the chosen option will then appear in the text
10403 * After the user chooses an option, its `data` will be used as a new value for the widget.
10404 * A `label` also can be specified for each option: if given, it will be shown instead of the
10405 * `data` in the dropdown menu.
10407 * This widget can be used inside an HTML form, such as a OO.ui.FormLayout.
10409 * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1].
10412 * // Example: A ComboBoxInputWidget.
10413 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10414 * value: 'Option 1',
10416 * { data: 'Option 1' },
10417 * { data: 'Option 2' },
10418 * { data: 'Option 3' }
10421 * $( 'body' ).append( comboBox.$element );
10424 * // Example: A ComboBoxInputWidget with additional option labels.
10425 * var comboBox = new OO.ui.ComboBoxInputWidget( {
10426 * value: 'Option 1',
10429 * data: 'Option 1',
10430 * label: 'Option One'
10433 * data: 'Option 2',
10434 * label: 'Option Two'
10437 * data: 'Option 3',
10438 * label: 'Option Three'
10442 * $( 'body' ).append( comboBox.$element );
10444 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options
10447 * @extends OO.ui.TextInputWidget
10450 * @param {Object} [config] Configuration options
10451 * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }`
10452 * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.MenuSelectWidget menu select widget}.
10453 * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where
10454 * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the
10455 * containing `<div>` and has a larger area. By default, the menu uses relative positioning.
10456 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10458 OO
.ui
.ComboBoxInputWidget
= function OoUiComboBoxInputWidget( config
) {
10459 // Configuration initialization
10460 config
= $.extend( {
10461 autocomplete
: false
10464 // ComboBoxInputWidget shouldn't support `multiline`
10465 config
.multiline
= false;
10467 // See InputWidget#reusePreInfuseDOM about `config.$input`
10468 if ( config
.$input
) {
10469 config
.$input
.removeAttr( 'list' );
10472 // Parent constructor
10473 OO
.ui
.ComboBoxInputWidget
.parent
.call( this, config
);
10476 this.$overlay
= config
.$overlay
|| this.$element
;
10477 this.dropdownButton
= new OO
.ui
.ButtonWidget( {
10478 classes
: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ],
10480 disabled
: this.disabled
10482 this.menu
= new OO
.ui
.MenuSelectWidget( $.extend(
10486 $floatableContainer
: this.$element
,
10487 disabled
: this.isDisabled()
10493 this.connect( this, {
10494 change
: 'onInputChange',
10495 enter
: 'onInputEnter'
10497 this.dropdownButton
.connect( this, {
10498 click
: 'onDropdownButtonClick'
10500 this.menu
.connect( this, {
10501 choose
: 'onMenuChoose',
10502 add
: 'onMenuItemsChange',
10503 remove
: 'onMenuItemsChange'
10507 this.$input
.attr( {
10509 'aria-owns': this.menu
.getElementId(),
10510 'aria-autocomplete': 'list'
10512 // Do not override options set via config.menu.items
10513 if ( config
.options
!== undefined ) {
10514 this.setOptions( config
.options
);
10516 this.$field
= $( '<div>' )
10517 .addClass( 'oo-ui-comboBoxInputWidget-field' )
10518 .append( this.$input
, this.dropdownButton
.$element
);
10520 .addClass( 'oo-ui-comboBoxInputWidget' )
10521 .append( this.$field
);
10522 this.$overlay
.append( this.menu
.$element
);
10523 this.onMenuItemsChange();
10528 OO
.inheritClass( OO
.ui
.ComboBoxInputWidget
, OO
.ui
.TextInputWidget
);
10533 * Get the combobox's menu.
10535 * @return {OO.ui.MenuSelectWidget} Menu widget
10537 OO
.ui
.ComboBoxInputWidget
.prototype.getMenu = function () {
10542 * Get the combobox's text input widget.
10544 * @return {OO.ui.TextInputWidget} Text input widget
10546 OO
.ui
.ComboBoxInputWidget
.prototype.getInput = function () {
10551 * Handle input change events.
10554 * @param {string} value New value
10556 OO
.ui
.ComboBoxInputWidget
.prototype.onInputChange = function ( value
) {
10557 var match
= this.menu
.getItemFromData( value
);
10559 this.menu
.selectItem( match
);
10560 if ( this.menu
.getHighlightedItem() ) {
10561 this.menu
.highlightItem( match
);
10564 if ( !this.isDisabled() ) {
10565 this.menu
.toggle( true );
10570 * Handle input enter events.
10574 OO
.ui
.ComboBoxInputWidget
.prototype.onInputEnter = function () {
10575 if ( !this.isDisabled() ) {
10576 this.menu
.toggle( false );
10581 * Handle button click events.
10585 OO
.ui
.ComboBoxInputWidget
.prototype.onDropdownButtonClick = function () {
10586 this.menu
.toggle();
10591 * Handle menu choose events.
10594 * @param {OO.ui.OptionWidget} item Chosen item
10596 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuChoose = function ( item
) {
10597 this.setValue( item
.getData() );
10601 * Handle menu item change events.
10605 OO
.ui
.ComboBoxInputWidget
.prototype.onMenuItemsChange = function () {
10606 var match
= this.menu
.getItemFromData( this.getValue() );
10607 this.menu
.selectItem( match
);
10608 if ( this.menu
.getHighlightedItem() ) {
10609 this.menu
.highlightItem( match
);
10611 this.$element
.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu
.isEmpty() );
10617 OO
.ui
.ComboBoxInputWidget
.prototype.setDisabled = function ( disabled
) {
10619 OO
.ui
.ComboBoxInputWidget
.parent
.prototype.setDisabled
.call( this, disabled
);
10621 if ( this.dropdownButton
) {
10622 this.dropdownButton
.setDisabled( this.isDisabled() );
10625 this.menu
.setDisabled( this.isDisabled() );
10632 * Set the options available for this input.
10634 * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }`
10637 OO
.ui
.ComboBoxInputWidget
.prototype.setOptions = function ( options
) {
10640 .addItems( options
.map( function ( opt
) {
10641 return new OO
.ui
.MenuOptionWidget( {
10643 label
: opt
.label
!== undefined ? opt
.label
: opt
.data
10651 * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget,
10652 * which is a widget that is specified by reference before any optional configuration settings.
10654 * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways:
10656 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10657 * A left-alignment is used for forms with many fields.
10658 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10659 * A right-alignment is used for long but familiar forms which users tab through,
10660 * verifying the current field with a quick glance at the label.
10661 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10662 * that users fill out from top to bottom.
10663 * - **inline**: The label is placed after the field-widget and aligned to the left.
10664 * An inline-alignment is best used with checkboxes or radio buttons.
10666 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout.
10667 * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information.
10669 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
10672 * @extends OO.ui.Layout
10673 * @mixins OO.ui.mixin.LabelElement
10674 * @mixins OO.ui.mixin.TitledElement
10677 * @param {OO.ui.Widget} fieldWidget Field widget
10678 * @param {Object} [config] Configuration options
10679 * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline'
10680 * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget.
10681 * The array may contain strings or OO.ui.HtmlSnippet instances.
10682 * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget.
10683 * The array may contain strings or OO.ui.HtmlSnippet instances.
10684 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
10685 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
10686 * For important messages, you are advised to use `notices`, as they are always shown.
10687 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
10688 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
10690 * @throws {Error} An error is thrown if no widget is specified
10692 OO
.ui
.FieldLayout
= function OoUiFieldLayout( fieldWidget
, config
) {
10693 // Allow passing positional parameters inside the config object
10694 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10695 config
= fieldWidget
;
10696 fieldWidget
= config
.fieldWidget
;
10699 // Make sure we have required constructor arguments
10700 if ( fieldWidget
=== undefined ) {
10701 throw new Error( 'Widget not found' );
10704 // Configuration initialization
10705 config
= $.extend( { align
: 'left' }, config
);
10707 // Parent constructor
10708 OO
.ui
.FieldLayout
.parent
.call( this, config
);
10710 // Mixin constructors
10711 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, {
10712 $label
: $( '<label>' )
10714 OO
.ui
.mixin
.TitledElement
.call( this, $.extend( {}, config
, { $titled
: this.$label
} ) );
10717 this.fieldWidget
= fieldWidget
;
10720 this.$field
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10721 this.$messages
= $( '<ul>' );
10722 this.$header
= $( '<span>' );
10723 this.$body
= $( '<div>' );
10725 if ( config
.help
) {
10726 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
10727 $overlay
: config
.$overlay
,
10731 classes
: [ 'oo-ui-fieldLayout-help' ],
10735 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
10736 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
10738 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
10740 this.$help
= this.popupButtonWidget
.$element
;
10742 this.$help
= $( [] );
10746 this.fieldWidget
.connect( this, { disable
: 'onFieldDisable' } );
10749 if ( this.fieldWidget
.getInputId() ) {
10750 this.$label
.attr( 'for', this.fieldWidget
.getInputId() );
10752 this.$label
.on( 'click', function () {
10753 this.fieldWidget
.simulateLabelClick();
10758 .addClass( 'oo-ui-fieldLayout' )
10759 .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget
.isDisabled() )
10760 .append( this.$body
);
10761 this.$body
.addClass( 'oo-ui-fieldLayout-body' );
10762 this.$header
.addClass( 'oo-ui-fieldLayout-header' );
10763 this.$messages
.addClass( 'oo-ui-fieldLayout-messages' );
10765 .addClass( 'oo-ui-fieldLayout-field' )
10766 .append( this.fieldWidget
.$element
);
10768 this.setErrors( config
.errors
|| [] );
10769 this.setNotices( config
.notices
|| [] );
10770 this.setAlignment( config
.align
);
10775 OO
.inheritClass( OO
.ui
.FieldLayout
, OO
.ui
.Layout
);
10776 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.LabelElement
);
10777 OO
.mixinClass( OO
.ui
.FieldLayout
, OO
.ui
.mixin
.TitledElement
);
10782 * Handle field disable events.
10785 * @param {boolean} value Field is disabled
10787 OO
.ui
.FieldLayout
.prototype.onFieldDisable = function ( value
) {
10788 this.$element
.toggleClass( 'oo-ui-fieldLayout-disabled', value
);
10792 * Get the widget contained by the field.
10794 * @return {OO.ui.Widget} Field widget
10796 OO
.ui
.FieldLayout
.prototype.getField = function () {
10797 return this.fieldWidget
;
10801 * Return `true` if the given field widget can be used with `'inline'` alignment (see
10802 * #setAlignment). Return `false` if it can't or if this can't be determined.
10804 * @return {boolean}
10806 OO
.ui
.FieldLayout
.prototype.isFieldInline = function () {
10807 // This is very simplistic, but should be good enough.
10808 return this.getField().$element
.prop( 'tagName' ).toLowerCase() === 'span';
10813 * @param {string} kind 'error' or 'notice'
10814 * @param {string|OO.ui.HtmlSnippet} text
10817 OO
.ui
.FieldLayout
.prototype.makeMessage = function ( kind
, text
) {
10818 var $listItem
, $icon
, message
;
10819 $listItem
= $( '<li>' );
10820 if ( kind
=== 'error' ) {
10821 $icon
= new OO
.ui
.IconWidget( { icon
: 'alert', flags
: [ 'warning' ] } ).$element
;
10822 } else if ( kind
=== 'notice' ) {
10823 $icon
= new OO
.ui
.IconWidget( { icon
: 'info' } ).$element
;
10827 message
= new OO
.ui
.LabelWidget( { label
: text
} );
10829 .append( $icon
, message
.$element
)
10830 .addClass( 'oo-ui-fieldLayout-messages-' + kind
);
10835 * Set the field alignment mode.
10838 * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline'
10841 OO
.ui
.FieldLayout
.prototype.setAlignment = function ( value
) {
10842 if ( value
!== this.align
) {
10843 // Default to 'left'
10844 if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value
) === -1 ) {
10848 if ( value
=== 'inline' && !this.isFieldInline() ) {
10851 // Reorder elements
10852 if ( value
=== 'top' ) {
10853 this.$header
.append( this.$label
, this.$help
);
10854 this.$body
.append( this.$header
, this.$field
);
10855 } else if ( value
=== 'inline' ) {
10856 this.$header
.append( this.$label
, this.$help
);
10857 this.$body
.append( this.$field
, this.$header
);
10859 this.$header
.append( this.$label
);
10860 this.$body
.append( this.$header
, this.$help
, this.$field
);
10862 // Set classes. The following classes can be used here:
10863 // * oo-ui-fieldLayout-align-left
10864 // * oo-ui-fieldLayout-align-right
10865 // * oo-ui-fieldLayout-align-top
10866 // * oo-ui-fieldLayout-align-inline
10867 if ( this.align
) {
10868 this.$element
.removeClass( 'oo-ui-fieldLayout-align-' + this.align
);
10870 this.$element
.addClass( 'oo-ui-fieldLayout-align-' + value
);
10871 this.align
= value
;
10878 * Set the list of error messages.
10880 * @param {Array} errors Error messages about the widget, which will be displayed below the widget.
10881 * The array may contain strings or OO.ui.HtmlSnippet instances.
10884 OO
.ui
.FieldLayout
.prototype.setErrors = function ( errors
) {
10885 this.errors
= errors
.slice();
10886 this.updateMessages();
10891 * Set the list of notice messages.
10893 * @param {Array} notices Notices about the widget, which will be displayed below the widget.
10894 * The array may contain strings or OO.ui.HtmlSnippet instances.
10897 OO
.ui
.FieldLayout
.prototype.setNotices = function ( notices
) {
10898 this.notices
= notices
.slice();
10899 this.updateMessages();
10904 * Update the rendering of error and notice messages.
10908 OO
.ui
.FieldLayout
.prototype.updateMessages = function () {
10910 this.$messages
.empty();
10912 if ( this.errors
.length
|| this.notices
.length
) {
10913 this.$body
.after( this.$messages
);
10915 this.$messages
.remove();
10919 for ( i
= 0; i
< this.notices
.length
; i
++ ) {
10920 this.$messages
.append( this.makeMessage( 'notice', this.notices
[ i
] ) );
10922 for ( i
= 0; i
< this.errors
.length
; i
++ ) {
10923 this.$messages
.append( this.makeMessage( 'error', this.errors
[ i
] ) );
10928 * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button,
10929 * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}),
10930 * is required and is specified before any optional configuration settings.
10932 * Labels can be aligned in one of four ways:
10934 * - **left**: The label is placed before the field-widget and aligned with the left margin.
10935 * A left-alignment is used for forms with many fields.
10936 * - **right**: The label is placed before the field-widget and aligned to the right margin.
10937 * A right-alignment is used for long but familiar forms which users tab through,
10938 * verifying the current field with a quick glance at the label.
10939 * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms
10940 * that users fill out from top to bottom.
10941 * - **inline**: The label is placed after the field-widget and aligned to the left.
10942 * An inline-alignment is best used with checkboxes or radio buttons.
10944 * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help
10945 * text is specified.
10948 * // Example of an ActionFieldLayout
10949 * var actionFieldLayout = new OO.ui.ActionFieldLayout(
10950 * new OO.ui.TextInputWidget( {
10951 * placeholder: 'Field widget'
10953 * new OO.ui.ButtonWidget( {
10957 * label: 'An ActionFieldLayout. This label is aligned top',
10959 * help: 'This is help text'
10963 * $( 'body' ).append( actionFieldLayout.$element );
10966 * @extends OO.ui.FieldLayout
10969 * @param {OO.ui.Widget} fieldWidget Field widget
10970 * @param {OO.ui.ButtonWidget} buttonWidget Button widget
10971 * @param {Object} config
10973 OO
.ui
.ActionFieldLayout
= function OoUiActionFieldLayout( fieldWidget
, buttonWidget
, config
) {
10974 // Allow passing positional parameters inside the config object
10975 if ( OO
.isPlainObject( fieldWidget
) && config
=== undefined ) {
10976 config
= fieldWidget
;
10977 fieldWidget
= config
.fieldWidget
;
10978 buttonWidget
= config
.buttonWidget
;
10981 // Parent constructor
10982 OO
.ui
.ActionFieldLayout
.parent
.call( this, fieldWidget
, config
);
10985 this.buttonWidget
= buttonWidget
;
10986 this.$button
= $( '<span>' );
10987 this.$input
= this.isFieldInline() ? $( '<span>' ) : $( '<div>' );
10991 .addClass( 'oo-ui-actionFieldLayout' );
10993 .addClass( 'oo-ui-actionFieldLayout-button' )
10994 .append( this.buttonWidget
.$element
);
10996 .addClass( 'oo-ui-actionFieldLayout-input' )
10997 .append( this.fieldWidget
.$element
);
10999 .append( this.$input
, this.$button
);
11004 OO
.inheritClass( OO
.ui
.ActionFieldLayout
, OO
.ui
.FieldLayout
);
11007 * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts},
11008 * which each contain an individual widget and, optionally, a label. Each Fieldset can be
11009 * configured with a label as well. For more information and examples,
11010 * please see the [OOjs UI documentation on MediaWiki][1].
11013 * // Example of a fieldset layout
11014 * var input1 = new OO.ui.TextInputWidget( {
11015 * placeholder: 'A text input field'
11018 * var input2 = new OO.ui.TextInputWidget( {
11019 * placeholder: 'A text input field'
11022 * var fieldset = new OO.ui.FieldsetLayout( {
11023 * label: 'Example of a fieldset layout'
11026 * fieldset.addItems( [
11027 * new OO.ui.FieldLayout( input1, {
11028 * label: 'Field One'
11030 * new OO.ui.FieldLayout( input2, {
11031 * label: 'Field Two'
11034 * $( 'body' ).append( fieldset.$element );
11036 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets
11039 * @extends OO.ui.Layout
11040 * @mixins OO.ui.mixin.IconElement
11041 * @mixins OO.ui.mixin.LabelElement
11042 * @mixins OO.ui.mixin.GroupElement
11045 * @param {Object} [config] Configuration options
11046 * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields.
11047 * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear
11048 * in the upper-right corner of the rendered field; clicking it will display the text in a popup.
11049 * For important messages, you are advised to use `notices`, as they are always shown.
11050 * @cfg {jQuery} [$overlay] Passed to OO.ui.PopupButtonWidget for help popup, if `help` is given.
11051 * See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
11053 OO
.ui
.FieldsetLayout
= function OoUiFieldsetLayout( config
) {
11054 // Configuration initialization
11055 config
= config
|| {};
11057 // Parent constructor
11058 OO
.ui
.FieldsetLayout
.parent
.call( this, config
);
11060 // Mixin constructors
11061 OO
.ui
.mixin
.IconElement
.call( this, config
);
11062 OO
.ui
.mixin
.LabelElement
.call( this, $.extend( {}, config
, { $label
: $( '<div>' ) } ) );
11063 OO
.ui
.mixin
.GroupElement
.call( this, config
);
11066 this.$header
= $( '<div>' );
11067 if ( config
.help
) {
11068 this.popupButtonWidget
= new OO
.ui
.PopupButtonWidget( {
11069 $overlay
: config
.$overlay
,
11073 classes
: [ 'oo-ui-fieldsetLayout-help' ],
11077 if ( config
.help
instanceof OO
.ui
.HtmlSnippet
) {
11078 this.popupButtonWidget
.getPopup().$body
.html( config
.help
.toString() );
11080 this.popupButtonWidget
.getPopup().$body
.text( config
.help
);
11082 this.$help
= this.popupButtonWidget
.$element
;
11084 this.$help
= $( [] );
11089 .addClass( 'oo-ui-fieldsetLayout-header' )
11090 .append( this.$icon
, this.$label
, this.$help
);
11091 this.$group
.addClass( 'oo-ui-fieldsetLayout-group' );
11093 .addClass( 'oo-ui-fieldsetLayout' )
11094 .prepend( this.$header
, this.$group
);
11095 if ( Array
.isArray( config
.items
) ) {
11096 this.addItems( config
.items
);
11102 OO
.inheritClass( OO
.ui
.FieldsetLayout
, OO
.ui
.Layout
);
11103 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.IconElement
);
11104 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.LabelElement
);
11105 OO
.mixinClass( OO
.ui
.FieldsetLayout
, OO
.ui
.mixin
.GroupElement
);
11107 /* Static Properties */
11113 OO
.ui
.FieldsetLayout
.static.tagName
= 'fieldset';
11116 * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based
11117 * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an
11118 * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively.
11119 * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples.
11121 * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It
11122 * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link
11123 * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as
11124 * some fancier controls. Some controls have both regular and InputWidget variants, for example
11125 * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and
11126 * often have simplified APIs to match the capabilities of HTML forms.
11127 * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets.
11129 * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms
11130 * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs
11133 * // Example of a form layout that wraps a fieldset layout
11134 * var input1 = new OO.ui.TextInputWidget( {
11135 * placeholder: 'Username'
11137 * var input2 = new OO.ui.TextInputWidget( {
11138 * placeholder: 'Password',
11141 * var submit = new OO.ui.ButtonInputWidget( {
11145 * var fieldset = new OO.ui.FieldsetLayout( {
11146 * label: 'A form layout'
11148 * fieldset.addItems( [
11149 * new OO.ui.FieldLayout( input1, {
11150 * label: 'Username',
11153 * new OO.ui.FieldLayout( input2, {
11154 * label: 'Password',
11157 * new OO.ui.FieldLayout( submit )
11159 * var form = new OO.ui.FormLayout( {
11160 * items: [ fieldset ],
11161 * action: '/api/formhandler',
11164 * $( 'body' ).append( form.$element );
11167 * @extends OO.ui.Layout
11168 * @mixins OO.ui.mixin.GroupElement
11171 * @param {Object} [config] Configuration options
11172 * @cfg {string} [method] HTML form `method` attribute
11173 * @cfg {string} [action] HTML form `action` attribute
11174 * @cfg {string} [enctype] HTML form `enctype` attribute
11175 * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout.
11177 OO
.ui
.FormLayout
= function OoUiFormLayout( config
) {
11180 // Configuration initialization
11181 config
= config
|| {};
11183 // Parent constructor
11184 OO
.ui
.FormLayout
.parent
.call( this, config
);
11186 // Mixin constructors
11187 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11190 this.$element
.on( 'submit', this.onFormSubmit
.bind( this ) );
11192 // Make sure the action is safe
11193 action
= config
.action
;
11194 if ( action
!== undefined && !OO
.ui
.isSafeUrl( action
) ) {
11195 action
= './' + action
;
11200 .addClass( 'oo-ui-formLayout' )
11202 method
: config
.method
,
11204 enctype
: config
.enctype
11206 if ( Array
.isArray( config
.items
) ) {
11207 this.addItems( config
.items
);
11213 OO
.inheritClass( OO
.ui
.FormLayout
, OO
.ui
.Layout
);
11214 OO
.mixinClass( OO
.ui
.FormLayout
, OO
.ui
.mixin
.GroupElement
);
11219 * A 'submit' event is emitted when the form is submitted.
11224 /* Static Properties */
11230 OO
.ui
.FormLayout
.static.tagName
= 'form';
11235 * Handle form submit events.
11238 * @param {jQuery.Event} e Submit event
11241 OO
.ui
.FormLayout
.prototype.onFormSubmit = function () {
11242 if ( this.emit( 'submit' ) ) {
11248 * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding,
11249 * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}.
11252 * // Example of a panel layout
11253 * var panel = new OO.ui.PanelLayout( {
11257 * $content: $( '<p>A panel layout with padding and a frame.</p>' )
11259 * $( 'body' ).append( panel.$element );
11262 * @extends OO.ui.Layout
11265 * @param {Object} [config] Configuration options
11266 * @cfg {boolean} [scrollable=false] Allow vertical scrolling
11267 * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel.
11268 * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element.
11269 * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content.
11271 OO
.ui
.PanelLayout
= function OoUiPanelLayout( config
) {
11272 // Configuration initialization
11273 config
= $.extend( {
11280 // Parent constructor
11281 OO
.ui
.PanelLayout
.parent
.call( this, config
);
11284 this.$element
.addClass( 'oo-ui-panelLayout' );
11285 if ( config
.scrollable
) {
11286 this.$element
.addClass( 'oo-ui-panelLayout-scrollable' );
11288 if ( config
.padded
) {
11289 this.$element
.addClass( 'oo-ui-panelLayout-padded' );
11291 if ( config
.expanded
) {
11292 this.$element
.addClass( 'oo-ui-panelLayout-expanded' );
11294 if ( config
.framed
) {
11295 this.$element
.addClass( 'oo-ui-panelLayout-framed' );
11301 OO
.inheritClass( OO
.ui
.PanelLayout
, OO
.ui
.Layout
);
11306 * Focus the panel layout
11308 * The default implementation just focuses the first focusable element in the panel
11310 OO
.ui
.PanelLayout
.prototype.focus = function () {
11311 OO
.ui
.findFocusable( this.$element
).focus();
11315 * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its
11316 * items), with small margins between them. Convenient when you need to put a number of block-level
11317 * widgets on a single line next to each other.
11319 * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper.
11322 * // HorizontalLayout with a text input and a label
11323 * var layout = new OO.ui.HorizontalLayout( {
11325 * new OO.ui.LabelWidget( { label: 'Label' } ),
11326 * new OO.ui.TextInputWidget( { value: 'Text' } )
11329 * $( 'body' ).append( layout.$element );
11332 * @extends OO.ui.Layout
11333 * @mixins OO.ui.mixin.GroupElement
11336 * @param {Object} [config] Configuration options
11337 * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout.
11339 OO
.ui
.HorizontalLayout
= function OoUiHorizontalLayout( config
) {
11340 // Configuration initialization
11341 config
= config
|| {};
11343 // Parent constructor
11344 OO
.ui
.HorizontalLayout
.parent
.call( this, config
);
11346 // Mixin constructors
11347 OO
.ui
.mixin
.GroupElement
.call( this, $.extend( {}, config
, { $group
: this.$element
} ) );
11350 this.$element
.addClass( 'oo-ui-horizontalLayout' );
11351 if ( Array
.isArray( config
.items
) ) {
11352 this.addItems( config
.items
);
11358 OO
.inheritClass( OO
.ui
.HorizontalLayout
, OO
.ui
.Layout
);
11359 OO
.mixinClass( OO
.ui
.HorizontalLayout
, OO
.ui
.mixin
.GroupElement
);
11363 //# sourceMappingURL=oojs-ui-core.js.map